LeetCode OJ-104. Maximum Depth of Binary Tree(求二叉树最大深度)

104. Maximum Depth of Binary Tree

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.


求二叉树最大深度,实际上是求二叉树中最远的子节点与根节点的距离,先想比较直观的思路,一个非空的二叉树的最大深度,即根节点的左右子节点的最大深度中较大的一个加上1,因为左右子节点到根节点还有1的距离。而现在需要计算的就是左右子节点的最大深度了,回想刚才起始的思路,计算左右子节点的最大深度不就是再去计算其子节点的最大深度加上1么,所有这里采用递归是比较容易实现的。使用递归的时候需要注意边界条件,在这里,边界条件就应该是节点为空,节点为空,那就不存在它到其父节点的距离了,返回0即可。具体代码如下:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxDepth(struct TreeNode* root) {
    int depth = 0;
    if (root) {
        int ldepth = maxDepth(root->left);
        int rdepth = maxDepth(root->right);
        depth = ldepth > rdepth ? ldepth + 1 : rdepth + 1;
    }
    
    return depth;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值