当前位置: 代码迷 >> 综合 >> JAVA程序设计:输出二叉树(LeetCode:655)
  详细解决方案

JAVA程序设计:输出二叉树(LeetCode:655)

热度:64   发布时间:2024-01-26 15:45:28.0

在一个 m*n 的二维字符串数组中输出二叉树,并遵守以下规则:

行数 m 应当等于给定二叉树的高度。
列数 n 应当总是奇数。
根节点的值(以字符串格式给出)应当放在可放置的第一行正中间。根节点所在的行与列会将剩余空间划分为两部分(左下部分和右下部分)。你应该将左子树输出在左下部分,右子树输出在右下部分。左下和右下部分应当有相同的大小。即使一个子树为空而另一个非空,你不需要为空的子树输出任何东西,但仍需要为另一个子树留出足够的空间。然而,如果两个子树都为空则不需要为它们留出任何空间。
每个未使用的空间应包含一个空的字符串""。
使用相同的规则输出子树。
示例 1:

输入:
1
/
2
输出:
[["", "1", ""],
["2", "", ""]]
示例 2:

输入:
1
/ \
2   3
\
4
输出:
[["", "", "", "1", "", "", ""],
["", "2", "", "", "", "3", ""],
["", "", "4", "", "", "", ""]]
示例 3:

输入:
1
/ \
2   5
/ 
3 
/ 
4 
输出:
[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]
注意: 二叉树的高度在范围 [1, 10] 中。

思路:两次dfs,第一次找到树的最大深度从而确定list的宽度,第二次即往矩阵相应位置填值即可。

class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; }
}class Solution {int step;List<String> res;List<List<String>> ans;public List<List<String>> printTree(TreeNode root) {step=0;res=new ArrayList<>();ans=new ArrayList<>();dfs(root,0);for(int i=0;i<=step;i++){for(int j=0;j<(1<<(step+1))-1;j++){res.add("");}ans.add(new ArrayList<>(res));res.clear();}dfs1(root,0,0,(1<<(step+1))-2);return ans;}private void dfs(TreeNode root, int depth){if(root==null) return;step=Math.max(step,depth);dfs(root.left,depth+1);dfs(root.right,depth+1);}private void dfs1(TreeNode root,int stepth,int id,int sum){if(root==null) return;ans.get(stepth).set(id+sum/2,String.valueOf(root.val));dfs1(root.left,stepth+1,id,sum/2);dfs1(root.right,stepth+1,id+sum/2+1,sum/2);}
}