-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_0701InsertIntoABinarySearchTree.java
44 lines (40 loc) · 1.24 KB
/
_0701InsertIntoABinarySearchTree.java
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
38
39
40
41
42
43
44
package com.heatwave.leetcode.problems;
public class _0701InsertIntoABinarySearchTree {
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (root.val >= val) {
root.left = insertIntoBST(root.left, val);
return root;
}
root.right = insertIntoBST(root.right, val);
return root;
}
}
class SolutionIteration {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
TreeNode node = root;
while (true) {
if (node.val >= val) {
if (node.left == null) {
node.left = new TreeNode(val);
break;
}
node = node.left;
} else {
if (node.right == null) {
node.right = new TreeNode(val);
break;
}
node = node.right;
}
}
return root;
}
}
}