LeetCode解题报告 104. Maximum Depth of Binary Tree [easy]

题目描述

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.

解题思路

题目要求返回一个二叉树的最大深度。
利用递归,深度优先搜索,dfs,注意如果根节点为空,返回0.

以下引用discuss中的一个解释,来体现每次的递归过程:

root: Node[0] has 2 children, Node[1] and Node[2]. and Node[2] has right child Node[3]

our first return will look like this return 1 + max(maxDepth(Node[1]), maxDepth(Node[2]));
we know maxDepth(Node[1]) = 0 because there are no children so when the program calls for maxDepth(Node[1] -> left) and maxDepth(Node[1] -> right) both those will return 0.

As for maxDepth(Node[2]) it will return 1 because Node[2] has 1 right child and to put it all together the recursion looks like this:
1 + max(maxDepth[Node[0 -> left], maxDepth(Node[0] -> right))
=>
1 + max(max(0,0), 1 + max(maxDepth(Node[1] - > left), maxDepth(Node[1] -> right)))
=>
1 + max(max(0,0), 1 + max(max(0,0), max(max(0,0),max(0,0))))
=>
1+max(0,1 + max(0,0))
=>1 + max(0,1)
=> 2

代码如下:
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root==NULL) {
            return 0;
        }
        int left_l=maxDepth(root->left);
        int right_l=maxDepth(root->right);
        if (left_l>right_l) {
            return left_l+1;
        }
        else
            return right_l+1;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值