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].

给一个二叉树,按照以下规则以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 题目汇总

最新文章

  1. IT人士必去的10个网站
  2. eclipse如何配置tomcat运行web项目时省略项目名称
  3. sqlserver 事务日志过大 收缩方法解决方案
  4. 对象序列化成Json字符串 及 反序列化成对象
  5. Python所有的错误都是从BaseException类派生的,常见的错误类型和继承关系
  6. 通过UserAgent判断设备为Android、Ios、Pc访问
  7. IBatis.Net XML文件配置
  8. WCF入门(8)
  9. 通用跨站脚本攻击(UXSS)
  10. 彻底解决_OBJC_CLASS_$_某文件名&quot;, referenced from:问题转
  11. Tip插件的使用
  12. jquery提供的插件无法删除cookie的解决办法
  13. An annotation based command line parser
  14. Spring boot整合ElasticSearch案例分享+bboss
  15. snmp简单测试
  16. 源码编译安装lnmp环境
  17. kafka_2.11-0.10.0.1生产者producer的Java实现
  18. Cocos2D-x-3.0 编译(Win7)
  19. 基于C#的机器学习--目录
  20. Luogu P2069 【松鼠吃果子】

热门文章

  1. 使用 xpath helper 提取网页链接
  2. linux用户的问题
  3. P4160 [SCOI2009]生日快乐[dfs]
  4. 2019-2020-1 20199301《Linux内核原理与分析》第八周作业
  5. 【python】Requests 库支持RESTFUL的几种方式
  6. bShare分享插件|自定义分享按钮|异步加载分享解决办法
  7. 解决:一个项目中写多个包含main函数的源文件并分别调试运行
  8. 海康相机开发(1) SDK安装和开发
  9. H5视频播放小结(video.js不好用!!!)
  10. JavaScript中的内存溢出与内存泄漏