-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum_depth_of_binary_tree.cpp
More file actions
88 lines (69 loc) · 1.63 KB
/
Copy pathmaximum_depth_of_binary_tree.cpp
File metadata and controls
88 lines (69 loc) · 1.63 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
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.
*/
#include <iostream>
#include <queue>
using namespace std;
//Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL)
{
}
};
// recursively
class Solution
{
public:
int maxDepth(TreeNode *root)
{
if (root == nullptr) return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
};
// unrecursively
class Solution2
{
public:
int maxDepth(TreeNode *root)
{
if (!root) return 0;
queue<TreeNode *> q;
TreeNode *cur = nullptr;
int level = 0, levelSize = 0;
q.push(root);
while (!q.empty()) {
if (levelSize == 0 ) {
levelSize = q.size();
level++;
}
cur = q.front();
q.pop();
levelSize--;
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
return level;
}
};
int main(int argc, char *argv[])
{
Solution sol;
Solution2 sol2;
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->right->right = new TreeNode(5);
cout << sol.maxDepth(root) << endl;
cout << sol2.maxDepth(root) << endl;
return 0;
}