二叉树最大深度和最小深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

递归形式

 

/**
     *输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
     */
    public int RMaxDeepth(TreeNode head){
        /**思路
         *  设置一个记录maxDeep,分别对根节点的左子树和右子树递归的进行遍历,如果存在左子树或者存在右子树,深度加1即可
         *  最后返回根节点左右子树中深度最大的那个即可。
         *
         * */
        if (head==null){
            return 0;
        }
        int maxDeep=1;//因为根节点算一层
        int leftDeep=0;
        int rightDeep=0;
        leftDeep=leftDeep+RMaxDeepth(head.left);
        rightDeep=rightDeep+RMaxDeepth(head.right);
        maxDeep+=Math.max(leftDeep,rightDeep);
        return maxDeep;
    }

非递归形式。采用层序遍历

/**
     * 非递归,这里使用了层序遍历
     */
    public int TreeDepth(TreeNode pRoot)
        {
            if(pRoot == null){
                return 0;
            }
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(pRoot);
            int depth = 0, count = 0, nextCount = 1;
            while(queue.size()!=0){
                TreeNode top = queue.poll();
                count++;
                if(top.left != null){
                    queue.add(top.left);
                }
                if(top.right != null){
                    queue.add(top.right);
                }
                if(count == nextCount){
                    nextCount = queue.size();
                    count = 0;
                    depth++;
                }
            }
            return depth;
        }

类比:给定二叉树,找到它的最小深度。最小深度是沿从根节点到最近的叶节点的最短路径上的节点数。

一个求最小深度,一个求最大深度。

/**
 * 给定二叉树,找到它的最小深度。最小深度是沿从根节点到最近的叶节点的最短路径上的节点数。
 */
public int MinDeepth(TreeNode head){
    /**思路
     * 这里还是用层序遍历的方法。
     *
     * */
    if (head==null)return 0;
    Queue<TreeNode> queue=new LinkedList<>();
    queue.add(head);
    int depth=1;//head为1层
    while (!queue.isEmpty())
    {
        int size=queue.size();
        for (int i=0;i<size;i++){//每次遍历这么一层
            TreeNode temp=queue.poll();
            if (temp.left!=null){
                queue.add(temp.left);
            }
            if (temp.right!=null){
                queue.add(temp.right);
            }
            if (temp.right==null&&temp.left==null){
                return depth;
            }
        }
        depth++;
    }
    return depth;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值