题目描述
方法思路
Recursive Solution
public class Solution {
//Memory Usage: 37.8 MB, less than 5.71%
//Runtime: 3 ms, faster than 100.00%
public List<List<String>> printTree(TreeNode root) {
int height = getHeight(root);
String[][] res = new String[height][(1 << height) - 1];
//<< 按位左移运算符。左操作数按位左移右操作数指定的位数
for(String[] arr:res)
Arrays.fill(arr,"");
//将指定的String值分配给指定的String数组的每个元素
List<List<String>> ans = new ArrayList<>();
fill(res, root, 0, 0, res[0].length);
for(String[] arr:res)
ans.add(Arrays.asList(arr));
//返回由指定数组支持的固定大小的列表
return ans;
}
public void fill(String[][] res, TreeNode root, int i, int l, int r) {
if (root == null)
return;
res[i][(l + r) / 2] = "" + root.val;
fill(res, root.left, i + 1, l, (l + r) / 2);
fill(res, root.right, i + 1, (l + r + 1) / 2, r);
}
public int getHeight(TreeNode root) {
if (root == null)
return 0;
return 1 + Math.max(getHeight(root.left), getHeight(root.right));
}
}
题目链接:
https://leetcode.com/problems/print-binary-tree/