DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Insert into binary search tree

Problem

TC: O(log(n))O(log(n))
SC: O(log(n))O(log(n)) since the recursive method will be called log(n)log(n) times

/**
 * 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) {
        return tree(root,val);
    }
    public TreeNode tree(TreeNode node, int val){
        ///base case
        if(node ==null) return new TreeNode(val);


        if(node.val > val){
            node.left  = tree(node.left,val);
        }
        else node.right = tree(node.right,val);

        return node;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)