二叉树的宽度和深度

一、深度

递归版本

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

非递归版本

思想:二叉树的深度就是指二叉树有几层,那么我们可以使用层序遍历来实现。

public static int getDeep(TreeNode root) {
        if(root == null) return 0;
        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);
        int count = 1; //每层的结点数
        int level = 1; //层数
        while(!list.isEmpty()) {
            int size = 0; //临时保存下层的结点数
            for(int i = 0; i < count; i++) {
                TreeNode p = list.removeFirst();
                if(p.left != null) {
                    size++;
                    list.addLast(p.left);
                }
                if(p.right != null) {
                    size++;
                    list.addLast(p.right);
                }
            }
            //如果下一层没有结点,则结束循环
            if(size == 0) break;
            count = size;
            level++;
        }
        return level;
    }

二、宽度

思想:二叉树的宽度就是最宽的那一层的节点数,所以还是需要层序遍历的思想,先计算每层的结点数,然后找出最大的。

public static int getWidth(TreeNode root) {
        if(root == null) return 0;
        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);
        int count = 1; //每层的结点数
        int width = 1; //宽度
        while(!list.isEmpty()) {
            int size = 0; //临时保存下层的结点数
            for(int i = 0; i < count; i++) {
                TreeNode p = list.removeFirst();
                if(p.left != null) {
                    size++;
                    list.addLast(p.left);
                }
                if(p.right != null) {
                    size++;
                    list.addLast(p.right);
                }
            }
            if(size == 0) break; //如果下一层没有结点,则结束循环
            if(size > width) width = size;
            count = size;
        }
        return width;
    }

 

posted @ 2018-08-16 11:05  neu_张康  阅读(4756)  评论(1编辑  收藏  举报