701. Insert into a Binary Search Tree
Problem
Insert val (not already present) into a BST and return the root of a valid BST. Any valid result is accepted.
Example: [4,2,7,1,3], val = 5 → [4,2,7,1,3,5]
Walk down as in a search until you fall off the tree; attach the new node there as a leaf. (Any valid BST is accepted; leaf insertion is the simplest.)
Complexity: O(h).
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
node = TreeNode(val)
if not root:
return node
cur = root
while True:
if val < cur.val:
if not cur.left:
cur.left = node
return root
cur = cur.left
else:
if not cur.right:
cur.right = node
return root
cur = cur.right
def inorder(n):
return inorder(n.left) + [n.val] + inorder(n.right) if n else []
for vals, v in (([4, 2, 7, 1, 3], 5), ([40, 20, 60, 10, 30, 50, 70], 25), ([], 5), ([4, 2, 7, 1, 3, None, None, None, None, None, None], 0)):
got = inorder(Solution().insertIntoBST(make_tree(vals), v))
assert got == sorted([x for x in vals if x is not None] + [v]) # still a BST holding every value
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
TreeNode cur = root;
while (true) {
if (val < cur.val) {
if (cur.left == null) { cur.left = new TreeNode(val); return root; }
cur = cur.left;
} else {
if (cur.right == null) { cur.right = new TreeNode(val); return root; }
cur = cur.right;
}
}
}
}
func insertIntoBST(root *TreeNode, val int) *TreeNode {
node := &TreeNode{Val: val}
if root == nil {
return node
}
for cur := root; ; {
if val < cur.Val {
if cur.Left == nil {
cur.Left = node
return root
}
cur = cur.Left
} else {
if cur.Right == nil {
cur.Right = node
return root
}
cur = cur.Right
}
}
}