We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1fd19a5 commit 67c9f71Copy full SHA for 67c9f71
C++/maximum-binary-tree-ii.cpp
@@ -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
31
+ tie(curr->right, node->left) = make_pair(node, curr->right);
32
+ return root;
33
34
+};
0 commit comments