701. Insert into a Binary Search Tree

问题
You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

如果root为空则将值直接添加到根节点。
辅助方法比较当前节点的值。
如当前值大于添加的值,则检测左子节点是否为空。
如不为空则递归左子节点。
如当前值小于添加的值,则检测右子节点是否为空。
如不为空则递归右子节点。

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null){
root = new TreeNode(val);
}
insert(root,val);
return root;
}

private void insert(TreeNode root, int val){
if (root.val < val){
if (root.right == null){
root.right = new TreeNode(val);
}
insert(root.right, val);
}
else if (root.val > val){
if (root.left == null){
root.left = new TreeNode(val);
}
insert(root.left, val);
}
return;
}
}
Author

Xander

Posted on

2022-04-14

Updated on

2022-04-13

Licensed under

Comments