-
Notifications
You must be signed in to change notification settings - Fork 257
/
max-tree.cpp
37 lines (36 loc) · 930 Bytes
/
max-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
// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param A: Given an integer array with no duplicates.
* @return: The root of max tree.
*/
TreeNode* maxTree(vector<int> A) {
vector<TreeNode *> nodeStack;
for (int i = 0; i < A.size(); ++i) {
auto node = new TreeNode(A[i]);
while (!nodeStack.empty() && A[i] > nodeStack.back()->val) {
node->left = nodeStack.back();
nodeStack.pop_back();
}
if (!nodeStack.empty()) {
nodeStack.back()->right = node;
}
nodeStack.emplace_back(node);
}
return nodeStack.front();
}
};