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. 2017-11-15 软件包 java.io学习

    接口摘要 一.接口Closeable 方法摘要:void:close();关闭此流并释放与此流关联的所有系统资源.如果已经关闭该流,则调用此方法无效 涉及的异常信息:IOException ----- ...

  2. java日期格式大全 format SimpleDateFormat

    http://www.cnblogs.com/loveyakamoz/archive/2011/08/18/2145047.html

  3. SQLite学习手册(数据表和视图)

    如何列出SQLite数据库中的所有表 SQLite数据库中的信息存在于一个内置表sqlite_master中,在查询器中可以用 select * from sqlite_master 来查看,如果只要 ...

  4. web服务器学习2---httpd-2.4.29虚拟目录及访问控制

    一 创建虚拟目录 环境准备: 系统:CentOS 7.4 软件:httpd-2.4.29 1.编辑主配置文件,添加命令运行子配置文件 vi /usr/local/httpd/conf/httpd.co ...

  5. 网络1711-1712班 c 语言评分总表一览

    学号 姓名 作业地址 PTA实验作业5分 PTA排名2分 阅读代码2分 总结1分 代码规范扣分-2--0 总分 是否推荐博客 1 **莹 http://www.cnblogs.com/wwwwxy12 ...

  6. c语言第1次作业

    一.PTA实验作业 题目1:7-3 温度转换 本题要求编写程序,计算华氏温度150°F对应的摄氏温度.计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为整型. 1 ...

  7. session 与 cookie (一)

    服务器信息临时存储 session篇 web.xml设置 <session-config> <session-timeout></session-timeout> ...

  8. kali使用

    1.kali安装后安装vmtools ①.vim /etc/apt/sources.list 添加中科大滚动版更新源 deb http://mirrors.ustc.edu.cn/kali kali- ...

  9. B+树介绍

    B+树 B+树和二叉树.平衡二叉树一样,都是经典的数据结构.B+树由B树和索引顺序访问方法(ISAM,是不是很熟悉?对,这也是MyISAM引擎最初参考的数据结构)演化而来,但是在实际使用过程中几乎已经 ...

  10. C# 使用 ffmpeg 进行音频转码

    先放一下 ffmpeg 的官方文档以及下载地址: 官方文档:http://ffmpeg.org/ffmpeg.html 下载地址:http://ffmpeg.org/download.html 用 f ...