701. Insert into a Binary Search Tree
# Medium
Solution 1: (add new value to leaf, don't change root)
Use helper function to insert new value as a leaf
Return original root in main function
class Solution {
public void helper(TreeNode root, int val) {
if(val > root.val) {
if(root.right != null)
helper(root.right, val);
else {
root.right = new TreeNode(val);
return;
}
}
else
if(root.left != null)
helper(root.left, val);
else {
root.left = new TreeNode(val);
return;
}
}
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null)
return new TreeNode(val);
helper(root, val);
return root;
}
}
Last updated
Was this helpful?