LeetCode104二叉树的最大深度

题目链接

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

题解

  • 递归
  • 递归出口是当前结点为空,则返回0
  • 如果非空,则该结点深度为左子树和右子树深度的最大值+1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Problem: LeetCode 104
// URL: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/
// Tags: Tree Recursion
// Difficulty: Easy

#include <iostream>
#include <algorithm>
using namespace std;

struct TreeNode{
TreeNode* left;
TreeNode* right;
int val;
TreeNode(int x):val(x), left(nullptr), right(nullptr){}
};

class Solution{
public:
int maxDepth(TreeNode* root){
if(nullptr==root)
return 0;
return max(maxDepth(root->left), maxDepth(root->right))+1;
}
};

int main()
{
cout << "helloworld" << endl;
// system("pause");
return 0;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!