Skip to content

Commit 67c9f71

Browse files
authored
Create maximum-binary-tree-ii.cpp
1 parent 1fd19a5 commit 67c9f71

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

C++/maximum-binary-tree-ii.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Time: O(h)
2+
// Space: O(1)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
16+
if (!root) {
17+
return new TreeNode(val);
18+
}
19+
20+
if (val > root->val) {
21+
auto node = new TreeNode(val);
22+
node->left = root;
23+
return node;
24+
}
25+
26+
auto curr = root;
27+
while (curr->right && curr->right->val > val) {
28+
curr = curr->right;
29+
}
30+
auto node = new TreeNode(val);
31+
tie(curr->right, node->left) = make_pair(node, curr->right);
32+
return root;
33+
}
34+
};

0 commit comments

Comments
 (0)