-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximum Depth of Binary Tree.cpp
135 lines (129 loc) · 2.83 KB
/
Maximum Depth of Binary Tree.cpp
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
/**
* 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:
/*recursive
int maxDepth(TreeNode* root) {
if(!root) {
return 0;
}
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return left > right ? left + 1 : right + 1;
}
*/
/*
confuse
int maxDepth(TreeNode* root) {
if(!root) {
return 0;
}
stack<TreeNode *> s;
TreeNode *cur, *pre = NULL;
bool noChild, visited;
s.push(root);
int depth = 0;
while(!s.empty()) {
if(s.size() > depth) {
depth = s.size();
}
cur = s.top();
noChild = false;
visited = false;
if(!cur->left && !cur->right) {
noChild = true;
}
if(pre && pre == cur->left) {
if(cur->right) {
s.push(cur->right);
}
else {
visited = true;
}
}
else if(pre && pre == cur->right) {
visited = true;
}
else {
if(cur->left) {
s.push(cur->left);
}
else if(cur->right) {
s.push(cur->right);
}
}
if(noChild || visited) {
pre = cur;
s.pop();
}
}
return depth;
}
*/
int maxDepth(TreeNode* root) {
if(root == NULL) {
return 0;
}
TreeNode *cur = NULL, *pre = NULL; //函数内一定要初始化!
stack<TreeNode *> s;
s.push(root);
int depth = 0;
while(!s.empty()) {
cur = s.top();
if(!pre || pre->left == cur || pre->right == cur) {
if(cur->left) {
s.push(cur->left);
}
else if(cur->right) {
s.push(cur->right);
}
}
else if(pre == cur->left) {
if(cur->right) {
s.push(cur->right);
}
}
else {
s.pop();
}
pre = cur;
if(s.size() > depth) {
depth = s.size();
}
}
return depth;
}
};
TreeNode *buildTree(int depth, int &val) {
TreeNode *root = new TreeNode(val);
if(depth == 0) {
return root;
}
root->left = buildTree(depth - 1, ++val);
root->right = buildTree(depth - 1, ++val);
return root;
}
int main() {
int val = 1;
// TreeNode *tree = buildTree(3, val);
TreeNode *tree = new TreeNode(0);
// tree->left = new TreeNode(2);
// tree->right = new TreeNode(3);
// tree->right->left = new TreeNode(4);
// tree->right->right = new TreeNode(5);
Solution s;
cout << s.maxDepth(tree) << endl;
return 0;
}