LeetCode 655. Print Binary Tree 格式问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yonggie/article/details/89843971

主要是想记录一下这个在遍历的时候也可以做其他动作的操作。

这题鬼畜的输出方式真是醉了。。

那么怎么做呢?

先找出深度,再通过深度算出宽度,怎么确定这些节点的位置?你看看下面Format这个方法,一边遍历一边改。

先算出深度宽度,然后做一个规模是  深度*宽度  全是 ""  的矩阵,在遍历的时候修改矩阵。

/**
 * 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) {
        int height=Height(root,0);
        //由高度算出宽度,不过注意,这个宽度不是2^(h-1)
        int width=(int)Math.pow(2,height)-1;
        
        List<List<String>> res=new ArrayList<>();
        //搞出来全是""的矩阵
        for(int i=0;i<height;i++){
            List<String> temp=new ArrayList<>();
            for(int j=0;j<width;j++)
                temp.add("");
            res.add(temp);
        }
        //修改值
        Format(res,root,0,0,width-1);
        return res;
    }
    //算出高度
    int Height(TreeNode root,int depth){
        if(root==null) return depth;
        return Math.max(Height(root.left,depth+1),Height(root.right,depth+1));
    }
    //保证修改的值在正确的位置center,
    void Format(List<List<String>> res,TreeNode root,int row,int left,int right){
        if(root==null) return;
        
        int center=(left+right)/2;
        res.get(row).set(center,String.valueOf(root.val));
        Format(res,root.left,row+1,left,center);
        Format(res,root.right,row+1,center+1,right);
    }
}

猜你喜欢

转载自blog.csdn.net/Yonggie/article/details/89843971