Skip to content

Commit 25de70c

Browse files
authored
Update Insert into a Binary Search Tree.java
1 parent 70bead3 commit 25de70c

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

Medium/Insert into a Binary Search Tree.java

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,27 @@
1212
* this.right = right;
1313
* }
1414
* }
15-
*/
15+
*/
1616
class Solution {
1717
public TreeNode insertIntoBST(TreeNode root, int val) {
18-
if (root == null) {
19-
return new TreeNode(val);
20-
} else if (root.val < val) {
21-
root.right = insertIntoBST(root.right, val);
22-
} else {
23-
root.left = insertIntoBST(root.left, val);
18+
TreeNode node = root;
19+
while (node != null) {
20+
if (val > node.val) {
21+
if (node.right == null) {
22+
node.right = new TreeNode(val);
23+
return root;
24+
} else {
25+
node = node.right;
26+
}
27+
} else {
28+
if (node.left == null) {
29+
node.left = new TreeNode(val);
30+
return root;
31+
} else {
32+
node = node.left;
33+
}
34+
}
2435
}
25-
return root;
36+
return new TreeNode(val);
2637
}
2738
}

0 commit comments

Comments
 (0)