题目:
Print a binary tree in an m*n 2D string array following these rules:
- The row number
m
should be equal to the height of the given binary tree. - The column number
n
should 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].
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<String>> printTree(TreeNode root) {
//给定二叉树,返回按期规定形式返回,即每层位置均保留上下层结构
//思路:先求出树的高度,即每层最大个数为2^h-1,然后根据每层所属的层数,将节点位置放置
//关键点:每个节点的坐标折中取值结果,左孩子的j=(i+j)/2-1;右孩子i=(i+j)/2+1
List<List<String>> list=new ArrayList<>();
if(root==null) return list;
int height=root==null?1:getHeight(root);
int row=height,col=(int)(Math.pow(2,height)-1);
List<String> subList=new ArrayList<>();
for(int i=0;i<col;i++){
//填充一行“”
subList.add("");
}
for(int j=0;j<row;j++){
//填充整个数据
list.add(new ArrayList<>(subList));
}
//递归实现
backtrace(root,list,0,row,0,col-1);
return list;
}
//递归将数据放入数组中,当判断到叶子节点是即停止
public void backtrace(TreeNode root,List<List<String>> list,int row,int totalRows,int i,int j){
if(root==null||row==totalRows) return ;
//在某个位置更改值用set,因为add会增加空间
list.get(row).set((i+j)/2,String.valueOf(root.val));
backtrace(root.left,list,row+1,totalRows,i,(i+j)/2-1);
backtrace(root.right,list,row+1,totalRows,(i+j)/2+1,j);
}
//求树高度
public int getHeight(TreeNode root){
if(root==null) return 0;
int left=getHeight(root.left);
int right=getHeight(root.right);
return Math.max(left,right)+1;
}
}