Print a binary tree in an m*n 2D string array following these rules:

  1. The row number m should be equal to the height of the given binary tree.
  2. The column number n should always be an odd number.
  3. The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.
  4. Each unused space should contain an empty string "".
  5. Print the subtrees following the same rules.

Example 1:

Input:
1
/
2
Output:
[["", "1", ""],
["2", "", ""]]

Example 2:

Input:
1
/ \
2 3
\
4
Output:
[["", "", "", "1", "", "", ""],
["", "2", "", "", "", "3", ""],
["", "", "4", "", "", "", ""]]

Example 3:

Input:
1
/ \
2 5
/
3
/
4
Output: [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""]
["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""]
["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""]
["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]]

Note: The height of binary tree is in the range of [1, 10].

这道题给了我们一棵二叉树,让我们以数组的形式打印出来。数组每一行的宽度是二叉树的最底层数所能有的最多结点数,存在的结点需要填入到正确的位置上。那么这道题我们就应该首先要确定返回数组的宽度,由于宽度跟数组的深度有关,所以我们首先应该算出二叉树的最大深度,直接写一个子函数返回这个最大深度,从而计算出宽度。下面就是要遍历二叉树从而在数组中加入结点值。我们先来看第一行,由于根结点只有一个,所以第一行只需要插入一个数字,不管这一行多少个位置,我们都是在最中间的位置插入结点值。下面来看第二行,我们仔细观察可以发现,如果我们将这一行分为左右两部分,那么插入的位置还是在每一部分的中间位置,这样我们只要能确定分成的部分的左右边界位置,就知道插入结点的位置了,所以应该是使用分治法的思路。在递归函数中,如果当前node不存在或者当前深度超过了最大深度直接返回,否则就给中间位置赋值为结点值,然后对于左子结点,范围是左边界到中间位置,调用递归函数,注意当前深度加1;同理对于右子结点,范围是中间位置加1到右边界,调用递归函数,注意当前深度加1,参见代码如下:

解法一:

class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
int h = getHeight(root), w = pow(, h) - ;
vector<vector<string>> res(h, vector<string>(w, ""));
helper(root, , w - , , h, res);
return res;
}
void helper(TreeNode* node, int i, int j, int curH, int height, vector<vector<string>>& res) {
if (!node || curH == height) return;
res[curH][(i + j) / ] = to_string(node->val);
helper(node->left, i, (i + j) / , curH + , height, res);
helper(node->right, (i + j) / + , j, curH + , height, res);
}
int getHeight(TreeNode* node) {
if (!node) return ;
return + max(getHeight(node->left), getHeight(node->right));
}
};

下面这种方法是层序遍历二叉树,使用了两个辅助队列来做,思路都一样,只不过是迭代的写法而已,关键还是在于左右边界的处理上,参见代码如下:

解法二:

class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
int h = getHeight(root), w = pow(, h) - , curH = -;
vector<vector<string>> res(h, vector<string>(w, ""));
queue<TreeNode*> q{{root}};
queue<pair<int, int>> idxQ{{{, w - }}};
while (!q.empty()) {
int n = q.size();
++curH;
for (int i = ; i < n; ++i) {
auto t = q.front(); q.pop();
auto idx = idxQ.front(); idxQ.pop();
if (!t) continue;
int left = idx.first, right = idx.second;
int mid = left + (right - left) / ;
res[curH][mid] = to_string(t->val);
q.push(t->left);
q.push(t->right);
idxQ.push({left, mid});
idxQ.push({mid + , right});
}
}
return res;
}
int getHeight(TreeNode* node) {
if (!node) return ;
return + max(getHeight(node->left), getHeight(node->right));
}
};

参考资料:

https://discuss.leetcode.com/topic/98381/java-recursive-solution

https://discuss.leetcode.com/topic/98503/java-iterative-level-order-traversal-with-queue

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Print Binary Tree 打印二叉树的更多相关文章

  1. [LeetCode] 655. Print Binary Tree 打印二叉树

    Print a binary tree in an m*n 2D string array following these rules: The row number m should be equa ...

  2. [LeetCode] Invert Binary Tree 翻转二叉树

    Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem wa ...

  3. [LeetCode] 257. Binary Tree Paths 二叉树路径

    Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 ...

  4. Leetcode 257 Binary Tree Paths 二叉树 DFS

    找到所有根到叶子的路径 深度优先搜索(DFS), 即二叉树的先序遍历. /** * Definition for a binary tree node. * struct TreeNode { * i ...

  5. [leetcode]257. Binary Tree Paths二叉树路径

    Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example ...

  6. LeetCode Invert Binary Tree 反转二叉树

    思路:递归解决,在返回root前保证该点的两个孩子已经互换了.注意可能给一个Null. C++ /** * Definition for a binary tree node. * struct Tr ...

  7. [LeetCode] Maximum Binary Tree 最大二叉树

    Given an integer array with no duplicates. A maximum tree building on this array is defined as follo ...

  8. LeetCode 145 Binary Tree Postorder Traversal(二叉树的兴许遍历)+(二叉树、迭代)

    翻译 给定一个二叉树.返回其兴许遍历的节点的值. 比如: 给定二叉树为 {1. #, 2, 3} 1 \ 2 / 3 返回 [3, 2, 1] 备注:用递归是微不足道的,你能够用迭代来完毕它吗? 原文 ...

  9. LeetCode 107 Binary Tree Level Order Traversal II(二叉树的层级顺序遍历2)(*)

    翻译 给定一个二叉树,返回从下往上遍历经过的每一个节点的值. 从左往右,从叶子到节点. 比如: 给定的二叉树是 {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 返回它从下 ...

随机推荐

  1. [poj2185]Milking Grid_KMP

    Milking Grid poj-2185 题目大意:给出一个字符矩阵,求最小覆盖矩阵(可以残余). 注释:$1\le R\le 10^5$,$1\le C \le 75$ 想法:和bzoj1355不 ...

  2. input输入框限制输入正整数、小数、字母、文字

    有的时候需要限制input的输入格式: 例如,输入大于0的正整数 <input onkeyup="if(this.value.length==1){this.value=this.va ...

  3. NOIP知识点

    基础算法 贪心 枚举 分治 二分 倍增 高精度 模拟 图论 图 最短路(dijkstra.spfa.floyd) 最小生成树(kruskal.prim) 并查集 拓扑排序 二分图染色 Tarjan 树 ...

  4. JAVA读取Excel中内容(HSSF和Workbook两种方法)

    内容添加,以前是用的HSSF,前几天帮同学写一个统计表用了Workbook,现在码一下. ---新内容(Workbook)--- 同学要统计一个xls表格,让表1里面的某一列内容对表2里面的每列进行匹 ...

  5. JavaScript(简介)【Javascript历史】

    学习一门知识应该了解其背景,很多人认为会用就行,起初我也是这么认为的,但后来才知道对起源的了解也很必要,从事javascript开发5年,今天开始总结一些笔记,分享下. 一.什么是JavaScript ...

  6. mongodb 复制(副本集)

    复制(副本集) 什么是复制 复制提供了数据的冗余备份,并在多个服务器上存储数据副本,提高了数据的可用性,并可以保证数据的安全性 复制还允许从硬件故障和服务中断中恢复数据 为什么要复制 数据备份 数据灾 ...

  7. 静态关键字static用法。

    static的特点:1,static是一个修饰符,用于修饰成员.2,static修饰的成员被所有的对象所共享.3,static优先于对象存在,因为static的成员随着类的加载就已经存在了. 4,st ...

  8. cord-in-a-box 2.0 安装指南

    [TOC] 这篇文章简要介绍了 Ciab2.0 的安装. 包括硬件, 软件环境的选择, Ciab2.0的实际部署架构, 安装过程等. 下面就先对 Ciab2.0 部署环境做简要介绍. 1. 概述 这一 ...

  9. openfalcon

    一.环境准备 操作系统:centos7(minimal,www.centos.org下载的包是CentOS-7-x86_64-Minimal-1611.iso) 1.1 更换阿里yum(个人习惯) 步 ...

  10. 12-TypeScript总结

    从前面的文章大家可以看出,TypeScript具有先天的优势,建议前端开发人员使用TypeScript进行开发,提升自己的面向对象开发思想与能力.: 1.微软开源的客户端脚本语言,是JavaScrip ...