二叉树的最大(小)深度

2 篇文章 0 订阅
1 篇文章 0 订阅

描述:给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的距离。
样例
给出一棵如下的二叉树:
这里写图片描述
思路:想到要采用递归调用的方法,但是不知道从何下手。后面参考网上,对左右子树都进行Max函数的调用,然后进行比较,较大者即为深度减1的量。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    int maxDepth(TreeNode *root) {
        // write your code here
    if(root == NULL) return 0;
    int left=maxDepth(root->left);
    int right=maxDepth(root->right);
    return max(left,right)+1;

    }
};

拓展:有最大深度,自然而然有最小深度。
思路:同样采用递归调用。只是有一点不同:因为深度是必须到叶子节点的距离,因此使用深度遍历时,不能单纯的比较左右子树的递归结果返回较小值,因为对于有单个孩子为空的节点,为空的孩子会返回0,但这个节点并非叶子节点,故返回的结果是错误的。因此,当发现当前处理的节点有单个孩子是空时,返回一个极大值INT_MAX,防止其干扰结果。

class Solution {
public:
    int minDepth(TreeNode *root) {
        if(!root) return 0;
        if(!root -> left && !root -> right) return 1;   //Leaf means should return depth.
        int leftDepth =  minDepth(root -> left);
        leftDepth = (leftDepth == 1 ? INT_MAX : leftDepth);
        int rightDepth = minDepth(root -> right);
        rightDepth = (rightDepth == 1 ? INT_MAX : rightDepth);  //If only one child returns 1, means this is not leaf, it does not return depth.
        return min(leftDepth, rightDepth)+1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值