题目描述
思路
首先,dfs确定树的高度height,根节点的高度为0。
其次,按照题干要求new一个List,按照对应行数和列数,逐个赋值为""。
最后,递归,root在矩阵中的位置[r,c]确定后,root的左右子节点位置就确定了。
自己在写的过程中发现边写边在List中插入新的List< Integer>会出现问题, 从r层递归到r+1层,r+1层存在多个节点,则插入新List可能造成重复。
代码
class Solution {
public List<List<String>> printTree(TreeNode root) {
int height = dfsHeight( root , 1 ) - 1 ;
int n = (int)Math.pow( 2 , height +1 ) - 1;
List<List<String>> ans = new ArrayList( );
for( int i = 0 ; i < height + 1 ; i++ ){
List<String> tmp = new ArrayList();
for( int j = 0 ; j < n ; j++ ){
tmp.add( "" );
}
ans.add( tmp );
}
dfs( root , 0 , ( n - 1 ) / 2 , n , height , ans );
return ans;
}
public int dfsHeight( TreeNode root , int curHeight ){
if( root==null ) return 0;
else if( root.left==null && root.right==null ) return curHeight ;
int left = dfsHeight( root.left , curHeight + 1 );
int right = dfsHeight( root.right , curHeight + 1 );
return Math.max( left , right ) ;
}
public void dfs( TreeNode root , int r , int c , int n , int height , List<List<String>> ans ){
if( root==null ) return;
ans.get( r ).set( c , root.val + "" );
int tmpC = (int)Math.pow( 2 , height - r - 1 );
dfs( root.left , r + 1 , c - tmpC , n , height , ans );
dfs( root.right , r + 1 , c + tmpC , n , height , ans );
}
}