[LeetCode] 655. Print Binary Tree 打印二叉树
Print a binary tree in an m*n 2D string array following these rules:
- The row number
mshould be equal to the height of the given binary tree. - The column number
nshould 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 ...
随机推荐
- Mybatis框架-update节点元素的使用
今天我们学习一下mybatis框架中的update节点元素的使用 需求:修改用户表中的一条数据记录,修改编号为21的用户的密码 UserMapper.xml UserMapper.java 编写测试方 ...
- LeetCode 1027. Longest Arithmetic Sequence
原题链接在这里:https://leetcode.com/problems/longest-arithmetic-sequence/ 题目: Given an array A of integers, ...
- SPA 首屏加载性能优化之 vue-cli3 拆包配置
前言 现在已经是vue-cli3.x webpack4.x 的时代了,但是网上很多拆包配置还是一些比较低版本的. 本文主要是分享自己的拆包踩坑经验. 主要是用了webpack4 的 splitC ...
- CF1237E 【Balanced Binary Search Trees】
首先我们要注意到一个性质:由于根与右子树的根奇偶性相同,那么根的奇偶性与\(N\)相同 然后我们发现对于一个完美树,他的左右两个儿子都是完美树 也就是说,一颗完美树是由两棵完美树拼成的 注意到另一个性 ...
- 58、Spark Streaming: DStream的output操作以及foreachRDD详解
一.output操作 1.output操作 DStream中的所有计算,都是由output操作触发的,比如print().如果没有任何output操作,那么,压根儿就不会执行定义的计算逻辑. 此外,即 ...
- 48、Spark SQL之与Spark Core整合之每日top3热点搜索词统计案例实战
一.概述 1.需求分析 数据格式: 日期 用户 搜索词 城市 平台 版本 需求: 1.筛选出符合查询条件(城市.平台.版本)的数据 2.统计出每天搜索uv排名前3的搜索词 3.按照每天的top3搜索词 ...
- UOJ269【清华集训2016】如何优雅地求和【数论,多项式】
题目描述:求 $$\sum_{k=0}^nf(k)\binom{n}{k}x^k(1-x)^{n-k}$$ 输入$n$,$f(x)$的次数上界$m$,$x$,$f(0,1,\ldots,m)$,对$9 ...
- 【POJ3083】Children of the Candy Corn
本题传送门 本题知识点:深度优先搜索 + 宽度优先搜索 本题题意是求三个路径长度,第一个是一直往左手边走的距离,第二个是一直往右手边走的距离,第三个是最短距离. 第三个很好办,就是一个简单的bfs的模 ...
- 2015-2016-2《Java程序设计》团队博客2
简易画图板介绍 一.功能结构图 二.主类设计 1.总体设计:在设计简易画图板时,根据程序功能的分类,包含了十二个文件,包括SimpleDraw.java,MenuContainer.java,Dra ...
- Tomcat启动时,控制台和IDEA控制台中文乱码解决方案
Tomcat启动时 控制台中文乱码 cmd控制台 IDEA控制台 解决方案 cmd乱码 打开Tomcat目录下的apache-tomcat-8.5.47\conf\logging.properties ...