-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum_Depth_of_Binary_Tree
49 lines (44 loc) · 1.22 KB
/
Maximum_Depth_of_Binary_Tree
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
Maximum Depth of Binary Tree
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.
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxHeight=1;
void helper(TreeNode *root, int h)
{
if (!root)
{
if (h>maxHeight) maxHeight=h;
return;
}
helper(root->left,h+1);
helper(root->right,h+1);
}
int maxDepth(TreeNode *root) {
if (!root) return 0;
int h=0;
helper(root,h);
return maxHeight;
}
};
REMARK:
1. Easy one. Just the normal way to deal with tree: create a recursive helper function within the main function maxDepth(TreeNode *root). In the helper function, first write stop condition and then the recursion. That's it.
2. However, after I see yu zhu's solution, his solution is much much better. He uses depth first search, then bang!
class Solution {
public:
int maxDepth(TreeNode *root) {
if (!root) return 0;
else return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};