[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 ...
随机推荐
- 2019年牛客多校第一场 C题Euclidean Distance 暴力+数学
题目链接 传送门 题意 给你\(n\)个数\(a_i\),要你在满足下面条件下使得\(\sum\limits_{i=1}^{n}(a_i-p_i)^2\)最小(题目给的\(m\)只是为了将\(a_i\ ...
- 第9期《python3接口自动化测试》课程,6月29号开学!
2019年 第9期<python3接口自动化测试>课程,6月29号开学! 主讲老师:上海-悠悠 上课方式:QQ群视频在线教学 本期上课时间:6月29号-7月28号,每周六.周日晚上20:3 ...
- background-image:url为空引发的两次请求问题
参考文章: https://blog.csdn.net/jsjhushilei/article/details/51101014 1.Nicholas 在 2009 年就开始推动各浏览器厂商,现在看起 ...
- 接口测试-Java代码实现接口请求并封装
前言:在接口测试和Java开发中对接口请求方法进行封装都非常有必要,无论是在我们接口测试的时候还是在开发自测,以及调用某些第三方接口时,都能为我们调用和调试接口提供便捷: Java实现对http请求的 ...
- linux 统计某个文件的行数
今日思语:迷茫的时候,看看身边那些优秀的人,他们还在那么努力,或许你就可以有点方向和动力了 在linux系统中,我们经常会对文件做行数统计,可以使用如下命令 wc -l file #file为具体的文 ...
- Optimal Marks SPOJ - OPTM(最小割)
传送门 论文<最小割模型在信息学竞赛中的应用>原题 二进制不同位上互不影响,那么就按位跑网络流 每一位上,确定的点值为1的与S连一条容量为INF的有向边.为0的与T连一条容量为INF的有向 ...
- Learning Vector Quantization
学习矢量量化. k近邻的缺点是你需要维持整个数据集的训练. 学习矢量量化算法(简称LVQ)是一种人工神经网络算法,它允许你选择要挂在多少个训练实例上,并精确地了解这些实例应该是什么样子. LVQ的表示 ...
- NVIDIA vGPU License服务器搭建详解
当配置有vGPU虚拟机发起License授权请求,授权服务器会根据License中所包含的GRID License版本,加载不同的vGPU驱动(普通驱动和专业Quodra卡驱动).目前vPC和vApp ...
- LSTM的结构
- javascript之命名空间方法封装
详细代码如下: Object.prototype.namespace= function(name){ var parts = name.split('.'); var current = this; ...