-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMax Tree.cpp
More file actions
28 lines (28 loc) · 743 Bytes
/
Max Tree.cpp
File metadata and controls
28 lines (28 loc) · 743 Bytes
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
class Solution {
public:
/**
* @param A: Given an integer array with no duplicates.
* @return: The root of max tree.
*/
TreeNode* maxTree(vector<int> A) {
// write your code here
stack<TreeNode*> stk;
for(auto a:A) {
TreeNode* node = new TreeNode(a), *t = NULL;
while(!stk.empty() && stk.top()->val < a) {
stk.top()->right = t;
t = stk.top();
stk.pop();
}
node->left = t;
stk.push(node);
}
TreeNode* root = NULL;
while(!stk.empty()) {
stk.top()->right = root;
root = stk.top();
stk.pop();
}
return root;
}
};