码迷,mamicode.com
首页 > 编程语言 > 详细

C语言递归之二叉树的最大深度

时间:2019-10-13 10:21:14      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:dep   一个   ble   签到   联系   https   etc   max   def   

题目描述

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

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

 

示例

给定二叉树 [3,9,20,null,null,15,7]

    3
   /   9  20
    /     15   7

返回它的最大深度 3 。

 

题目要求

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 int maxDepth(struct TreeNode* root){
11 
12 }

 

题解

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 int _max(int a,int b){
11     return a>b?a:b;
12 }
13 
14 int maxDepth(struct TreeNode* root){
15     if(root==NULL)return 0;
16 /*
17     加这三行会快一些,在数据量小的时候(上限高)
18     if(root->left==NULL&&root->right==NULL)return 1;
19     else if(root->left==NULL)return maxDepth(root->right)+1;
20     else if(root->right==NULL)return maxDepth(root->left)+1;
21 */
22     return 1+_max(maxDepth(root->left),maxDepth(root->right));
23 }

 

 

签到递归题,递归题只要情况考虑周到了,尤其是根节点为空的情况,就应该不会写错。

 

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

C语言递归之二叉树的最大深度

标签:dep   一个   ble   签到   联系   https   etc   max   def   

原文地址:https://www.cnblogs.com/shi-champion/p/11665071.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!