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.
Example 1:
Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
在二叉搜索树中插入节点
思路:
BST插入后只要具备BST特性就行,因为没有要求是平衡树,所以不需要做旋转变换
当root==null时,直接创建新的节点作为root
root != null时,先找到需要插入的位置,再创建新的节点
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode cur = root;
while(true) {
if(cur.val < val) {
if(cur.right != null) {
cur = cur.right;
} else {
cur.right = new TreeNode(val);
break;
}
} else {
if(cur.left != null) {
cur = cur.left;
} else {
cur.left = new TreeNode(val);
break;
}
}
}
return root;
}