104. Maximum Depth of Binary Tree(C语言)

104. Maximum Depth of Binary Tree(C语言)

求二叉树最大深度

题目

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:
在这里插入图片描述
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2

Constraints:
The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100

解答

选用递归的方法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

int Tra(struct TreeNode* root)
{
    if(root == NULL)
        return 0;
    
    int left_max = Tra(root->left);
    int right_max = Tra(root->right);
    return (left_max >= right_max) ? left_max+1 : right_max+1;
}
int maxDepth(struct TreeNode* root){
    int ret;
    if(root == NULL) ret = 0;
    else ret = Tra(root);
    return ret;
}

总结

看到这个题时,想到两个思路:
(1)遍历二叉树,用一个int变量存储最大深度,不断迭代;
(2)用递归的方式,把一棵大树一层层看作一个个小树,相当于求每个小树的最大深度,一个树的深度 = max(左子树深度,右子树深度)+1。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值