-
Notifications
You must be signed in to change notification settings - Fork 15
/
insert-node-in-a-binary-search-tree.java
88 lines (78 loc) · 2.12 KB
/
insert-node-in-a-binary-search-tree.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
// public TreeNode insertNode(TreeNode root, TreeNode node) {
// // write your code here
// if (root == null) {
// return node;
// }
// insertHelper(root, node);
// return root;
// }
// public void insertHelper(TreeNode parent, TreeNode node) {
// if (parent == null) return;
// if (parent.val < node.val) {
// if (parent.right == null) {
// parent.right = node;
// } else {
// insertHelper(parent.right, node);
// }
// } else {
// if (parent.left == null) {
// parent.left = node;
// } else {
// insertHelper(parent.left, node);
// }
// }
// }
// public TreeNode insertNode(TreeNode root, TreeNode node) {
// // write your code here
// if (root == null) {
// return node;
// }
// if (root.val < node.val) {
// root.right = insertNode(root.right, node);
// } else {
// root.left = insertNode(root.left, node);
// }
// return root;
// }
public TreeNode insertNode(TreeNode root, TreeNode node) {
// write your code here
if (root == null) {
return node;
}
TreeNode runner = root;
TreeNode parent = null;
while (runner != null) {
parent = runner;
if (runner.val < node.val) {
runner = runner.right;
} else {
runner = runner.left;
}
}
// if (parent != null) {
if (parent.val < node.val) {
parent.right = node;
} else {
parent.left = node;
}
// }
return root;
}
}