-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTreeInsert.java
More file actions
49 lines (44 loc) · 1.31 KB
/
BinarySearchTreeInsert.java
File metadata and controls
49 lines (44 loc) · 1.31 KB
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
45
46
47
48
49
package leetcode;
import utils.TreeNode;
import utils.Trees;
/**
* BinarySearchTreeInsert
* https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
*
* @since 2020-09-30
*/
public class BinarySearchTreeInsert {
public static void main(String[] args) {
Integer[] values = new Integer[]{4, 2, 7, 1, 3};
TreeNode head = Trees.fromIntegers(values);
BinarySearchTreeInsert sol = new BinarySearchTreeInsert();
TreeNode res = sol.insertIntoBST(head, 5);
System.out.println();
}
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val); // null插入值就是新的树
}
TreeNode curr = root;
while (curr != null) {
if (val > curr.val) {
if (curr.right == null) {
curr.right = new TreeNode(val);
break;
} else {
curr = curr.right;
}
} else if (val < curr.val) {
if (curr.left == null) {
curr.left = new TreeNode(val);
break;
} else {
curr = curr.left;
}
} else {
break;
}
}
return root;
}
}