Leetcode 701. Insert into a Binary Search Tree
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. The function should return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
A binary search tree is a binary tree where for every node, the values in its left subtree are less, and the values in its right subtree are greater.
/**
* 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) {
return new TreeNode(val);
}
TreeNode current = root;
while (true) {
if (val < current.val) {
if (current.left == null) {
current.left = new TreeNode(val);
break;
} else {
current = current.left;
}
} else {
if (current.right == null) {
current.right = new TreeNode(val);
break;
} else {
current = current.right;
}
}
}
return root;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?