forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum-binary-tree.cpp
More file actions
31 lines (30 loc) · 894 Bytes
/
maximum-binary-tree.cpp
File metadata and controls
31 lines (30 loc) · 894 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
29
30
31
// Time: O(n)
// Space: O(n)
/**
* 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:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
// https://github.com/kamyu104/LintCode/blob/master/C++/max-tree.cpp
vector<TreeNode *> nodeStack;
for (int i = 0; i < nums.size(); ++i) {
auto node = new TreeNode(nums[i]);
while (!nodeStack.empty() && nums[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();
}
};