LeetCode 104. Maximum Depth of Binary Tree && Minimum Depth of Binary

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

本题目是简单的二叉树深度问题,二叉树是每个节点最多有两个子树的树结构,二叉树还有递归定义:

二叉树是n(n>=0)个有限结点构成的集合。N=0称为空二叉树;n>0的二叉树由一个根结点和两互不相交的,分别称为左子树和右子树的二叉树构成。

二叉树中任何结点的第1个子树称为其左子树,左子树的根称为该结点的左孩子;二叉树中任何结点的第2个子树称为其右子树,左子树的根称为该结点的右孩子。

更多二叉树的性质和实现:见luoweifu的博客 二叉树(1)——二叉树的定义和递归实现

利用递归求二叉树的最大深度:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
        
        if(root == null){
            return 0;
        }
        
        int leftMaxDepth = maxDepth(root.left);
        int rightMaxDepth = maxDepth(root.right);
        return 1 + Math.max(leftMaxDepth,rightMaxDepth);
    }
}

简单解释:将每个结点都看做根节点,如果结点为空,则返回0,此为递归的出口,如果不为空,则深度至少为1,分别求其左子树和右子树的深度,进行比较,即可求出最大深度。

最近看到了求二叉树最小深度:

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

和求二叉树的最大深度不同,最小深度的计算需要考虑更多,当根结点只有左子树或者右子树,其深度的计算不能包含另一部分的计算:

代码如下:

public class Solution {
    public int run(TreeNode root) {
        if(root==null)
            return 0;
        if(root.left==null&&root.right==null)
            return 1;
        if(root.left==null)<span style="line-height: 25.2px; font-family: arial, STHeiti, "Microsoft YaHei", 宋体;">// 当前结点左子树为空,只有右子树</span>
            return run(root.right)+1;
        if(root.right==null)// 当前结点右子树为空,只有左子树
            return run(root.left)+1;
        return Math.min(run(root.left),run(root.right))+1;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值