LeetCode:二叉树的最大深度(C语言)

1、问题概述:给一个二叉树,返回最大深度(深度:根节点到最远子节点路径上的节点数)

2、分析:

(1)判断是否为空树

(2)左子数深度为m

(3)右子树深度为n

(4)左右字数进行比较:m>n ? m+1 : n+1

 3、代码

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

法1:
int maxDepth(struct TreeNode* root) {
    int max=0;  // 存放子树的深度
    int leftMax=0;
    int rightMax=0;
    if(root!=NULL){
        max++;   // 当root不为空时,深度先加1
        leftMax=maxDepth(root->left);   // 左子树深度
        rightMax=maxDepth(root->right); // 右子树深度
        max+=leftMax>rightMax?leftMax:rightMax;  // 当前字数的深度
    }
    return max;
}



-----------------------------------------------------------------------------------------
法2:
int maxDepth(struct TreeNode* root) {
    int max=0;  // 存放子树的深度
    if(!root) return max;
    int leftMax=maxDepth(root->left);
    int rightMax=maxDepth(root->right);

    if(!leftMax){
        max=rightMax+1;
    }else if(!rightMax){
         max=leftMax+1;
    }else{
        max=leftMax > rightMax ? leftMax+1 : rightMax+1;
    }

    return max;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值