打印二叉树

版权声明:版权所有by [email protected] https://blog.csdn.net/leechengqian/article/details/88048612

TreeNode实现同LeetCode:

public class TreeNode {
    Integer val;
    TreeNode left;
    TreeNode right;
    //TreeNode(Integer x) { val = x; }
    TreeNode(int x) {
        val = x;
        left=null;
        right=null;
    }
}

保留二叉树层次结构及节点相对位置,使用tab填充:

public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        int depth=1;
        depth+=Math.max(maxDepth(root.left),maxDepth(root.right));
        return depth;
    }

    public void printTree(TreeNode root){
        int depth=maxDepth(root);
        //然后就是层次遍历,在打印每一层的节点之前和之后打印tab。子节点的位置根据父节点的位置计算。
        if(root==null)
            return;
        Queue<TreeNode> queue=new LinkedList<TreeNode>();

        HashMap<TreeNode,Integer> posMap=new HashMap<TreeNode, Integer>();//记录节点位置。
        queue.offer(root);
        int level=1,levelCount=1,nextlevelCount=0;//记录当前层号及层节点数
        posMap.put(root,(int)Math.pow(2,depth-level));
        while(!queue.isEmpty()){
            TreeNode temp=queue.poll();
            for(int i=0;i<posMap.get(temp);i++)
                System.out.print("\t");
            System.out.print(temp.val);

            if(temp.left!=null){
                nextlevelCount++;
                posMap.put(temp.left,posMap.get(temp)-(int)Math.pow(2,depth-(level+1)));
                queue.offer(temp.left);

            }
            if(temp.right!=null){
                nextlevelCount++;
                posMap.put(temp.right,posMap.get(temp)+(int)Math.pow(2,depth-(level+1)));
                queue.offer(temp.right);
            }
            levelCount--;
            if (levelCount==0)//开始打印下一层
            {
                levelCount=nextlevelCount;
                level++;
                nextlevelCount=0;
                System.out.println();
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/leechengqian/article/details/88048612