LeetCode104 Maximum Depth of Binary Tree

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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.

样例

1
2
3
4
5
6
7
8
9
Input:   
1
/ \
2 3
/ \
4 5

Output:
3

思路

求二叉树的最大深度。

dfs遍历一遍即可,当前最大深度为左右子树深度的最大值加1!

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
else return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
分享到 评论