[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 equal to the height of the given binary tree. - The column number
n
should always be an odd number. - 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.
- Each unused space should contain an empty string
""
. - 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].
给一个二叉树,按照以下规则以m * n二维数组的形式打印出来:
1. 行号m应该等于给定二叉树的高度。
2. 列号n应始终为奇数。
3. 根节点的值(以字符串格式)应该放在它可以放入的第一行的正中间。 根节点所属的列和行将剩余空间分成两部分(左下部分和右下部分)。 您应该在左下部分打印左子树,并在右下部分打印右子树。 左下部和右下部应具有相同的尺寸。 即使一个子树不是,而另一个子树不是,你也不需要为无子树打印任何东西,但仍然需要留出与其他子树一样大的空间。 但是,如果两个子树都没有,那么您不需要为它们留出空间。
4. 每个未使用的空间应包含一个空字符串""。
5. 按照相同的规则打印子树。
解法:递归(Recursion),首先求出二叉树的深度来确定列,二维数组的列是2 ** height -1,height是二叉树深度。然后递归处理每一层,每一行中根节点的位置是:pos-2**(height - h - 1),pos是上一层的根节点的位置。
Java:
public List<List<String>> printTree(TreeNode root) {
List<List<String>> res = new LinkedList<>();
int height = root == null ? 1 : getHeight(root);
int rows = height, columns = (int) (Math.pow(2, height) - 1);
List<String> row = new ArrayList<>();
for(int i = 0; i < columns; i++) row.add("");
for(int i = 0; i < rows; i++) res.add(new ArrayList<>(row));
populateRes(root, res, 0, rows, 0, columns - 1);
return res;
} public void populateRes(TreeNode root, List<List<String>> res, int row, int totalRows, int i, int j) {
if (row == totalRows || root == null) return;
res.get(row).set((i+j)/2, Integer.toString(root.val));
populateRes(root.left, res, row+1, totalRows, i, (i+j)/2 - 1);
populateRes(root.right, res, row+1, totalRows, (i+j)/2+1, j);
} public int getHeight(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(getHeight(root.left), getHeight(root.right));
}
Python:
class Solution(object):
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
def get_height(node):
return 0 if not node else 1 + max(get_height(node.left), get_height(node.right)) def update_output(node, row, left, right):
if not node:
return
mid = (left + right) / 2
self.output[row][mid] = str(node.val)
update_output(node.left, row + 1 , left, mid - 1)
update_output(node.right, row + 1 , mid + 1, right) height = get_height(root)
width = 2 ** height - 1
self.output = [[''] * width for i in xrange(height)]
update_output(node=root, row=0, left=0, right=width - 1)
return self.output
Python:
class Solution(object):
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
def get_height(node):
if not node:
return 0
return 1 + max(get_height(node.left), get_height(node.right)) rows = get_height(root)
cols = 2 ** rows - 1
res = [['' for _ in range(cols)] for _ in range(rows)] def traverse(node, level, pos):
if not node:
return
left_padding, spacing = 2 ** (rows - level - 1) - 1, 2 ** (rows - level) - 1
index = left_padding + pos * (spacing + 1)
print(level, index, node.val)
res[level][index] = str(node.val)
traverse(node.left, level + 1, pos << 1)
traverse(node.right, level + 1, (pos << 1) + 1)
traverse(root, 0, 0)
return res
Python:
class Solution(object):
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
import math
def dfs(root, h):
if root:
return max(dfs(root.left,h+1), dfs(root.right,h+1))
else :
return h
height = dfs(root, 0)
width = 2 ** height -1
# 初始化
res = [ ["" for j in range(width)] for i in range(height)]
# dfs print
def dfs_print(res,root,h,pos):
if root:
res[h - 1][pos] = '%d' % root.val
dfs_print(res, root.left, h+1, pos-2**(height - h - 1))
dfs_print(res, root.right, h+1, pos+2**(height - h - 1))
dfs_print(res,root,1,width/2)
return res
Python:
# Time: O(h * 2^h)
# Space: O(h * 2^h)
class Solution(object):
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
def getWidth(root):
if not root:
return 0
return 2 * max(getWidth(root.left), getWidth(root.right)) + 1 def getHeight(root):
if not root:
return 0
return max(getHeight(root.left), getHeight(root.right)) + 1 def preorderTraversal(root, level, left, right, result):
if not root:
return
mid = left + (right-left)/2
result[level][mid] = str(root.val)
preorderTraversal(root.left, level+1, left, mid-1, result)
preorderTraversal(root.right, level+1, mid+1, right, result) h, w = getHeight(root), getWidth(root)
result = [[""] * w for _ in xrange(h)]
preorderTraversal(root, 0, 0, w-1, result)
return result
C++:
class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
int h = getHeight(root), w = pow(2, h) - 1;
vector<vector<string>> res(h, vector<string>(w, ""));
helper(root, 0, w - 1, 0, 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) / 2] = to_string(node->val);
helper(node->left, i, (i + j) / 2, curH + 1, height, res);
helper(node->right, (i + j) / 2 + 1, j, curH + 1, height, res);
}
int getHeight(TreeNode* node) {
if (!node) return 0;
return 1 + max(getHeight(node->left), getHeight(node->right));
}
};
C++:
class Solution {
public:
vector<vector<string>> printTree(TreeNode* root) {
int h = getHeight(root), w = pow(2, h) - 1, curH = -1;
vector<vector<string>> res(h, vector<string>(w, ""));
queue<TreeNode*> q{{root}};
queue<pair<int, int>> idxQ{{{0, w - 1}}};
while (!q.empty()) {
int n = q.size();
++curH;
for (int i = 0; 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) / 2;
res[curH][mid] = to_string(t->val);
q.push(t->left);
q.push(t->right);
idxQ.push({left, mid});
idxQ.push({mid + 1, right});
}
}
return res;
}
int getHeight(TreeNode* node) {
if (!node) return 0;
return 1 + max(getHeight(node->left), getHeight(node->right));
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 655. Print Binary Tree 打印二叉树的更多相关文章
- [LeetCode] Print Binary Tree 打印二叉树
Print a binary tree in an m*n 2D string array following these rules: The row number m should be equa ...
- LeetCode 655. Print Binary Tree (C++)
题目: Print a binary tree in an m*n 2D string array following these rules: The row number m should be ...
- LC 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 ...
- 【LeetCode】655. Print Binary Tree 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...
- LeetCode 654. Maximum Binary Tree最大二叉树 (C++)
题目: Given an integer array with no duplicates. A maximum tree building on this array is defined as f ...
- leetcode 226 Invert Binary Tree 翻转二叉树
大牛没有能做出来的题,我们要好好做一做 Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Tri ...
- [LeetCode] 654. Maximum Binary Tree 最大二叉树
Given an integer array with no duplicates. A maximum tree building on this array is defined as follo ...
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...
- (二叉树 递归) leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that ...
随机推荐
- java处理异常的机制关键字为throw和throws
在异常处理的过程中,throws和throw的区别是? throws:是在方法上对一个方法进行声明,而不进行处理,而是向上传,谁调用谁处理. throw:是在具体的抛出一个异常类型. throws的栗 ...
- py3+requests+json+xlwt,爬取拉勾招聘信息
在拉勾搜索职位时,通过谷歌F12抓取请求信息 发现请求是一个post请求,参数为: 返回的是json数据 有了上面的基础,我们就可以构造请求了 然后对获取到的响应反序列化,这样就获取到了json格式的 ...
- 微信小程序——获取当天的前一个月至后一个月
看标题也不知道你有没有明白我想表达的意思,先上个动态图吧~ 需要分析: 1.获取当前日期的前一个月,后一个月和当月.比如说现在是7月5号,我需要得到6月5号至8月5号的日期,同时还要返回当前的星期. ...
- WinDbg常用命令系列---!handle
!handle 简介 !handle扩展显示有关目标系统中一个或所有进程拥有的一个或多个句柄的信息. 使用形式 用户模式!handle [Handle [UMFlags [TypeName]]] !h ...
- jaeger使用yugabyte作为后端存储的尝试以及几个问题
前边写过使用scylladb 做为jaeger 的后端存储,还是一个不错选择的包括性能以及 兼容性,对于 yugabyte 当前存在兼容性的问题,需要版本的支持,或者尝试进行一些变动 create 语 ...
- velero 备份、迁移 kubernetes 应用以及持久化数据卷
velero 是heptio 团队开源的kubernetes 应用以及持久化数据卷备份以及迁移的解决方案,以前的名字为ark 包含以下特性: 备份集群以及恢复 copy 当前集群的资源到其他集群 复制 ...
- urql 高度可自定义&&多功能的react graphql client
urql 是一个很不错的graphql client,使用简单,功能强大,通过exchanges 实现了完整的自定义特性 通过urql 的exchanges 我们可以实现灵活的cache策略 参考资料 ...
- sqler 集成 terraform v0.12 生成资源部署文件
terraform v0.12 发布了,有好多新功能的添加,包括语法的增强,新函数的引入,更好的开发提示 只是当前对于一些老版本的provider 暂时还不兼容,但是大部分官方的provider 都是 ...
- 函数(定义、参数、return、变量、作用域、预解析)
一.函数定义 1.方式一 function 函数名(参数){ 函数体 }——————函数声明的方法 function fn(a){ console.log(a); }: 2.方式二 ...
- 捷配制作PCB流程
https://www.jiepei.com/orderprocess.html 以我的板子为例 查看下自己板子的信息 切换到mm 键盘 Q 压缩PCB文件 付款什么的自己哈 改天我有贴片的订单的时候 ...