My LeetCode Diary - Day22 BinaryTree

235. Lowest Common Ancestor of a Binary Search Tree

Link

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
        if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
        return root;
    }
}

701. Insert into a Binary Search Tree

Link

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) 
            return new TreeNode(val);
            
        if (root.val < val){
            root.right = insertIntoBST(root.right, val); 
        }else if (root.val > val){
            root.left = insertIntoBST(root.left, val); 
        }
        return root;
    }
}

450. Delete Node in a BST

Link

class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        root = delete(root,key);
        return root;
    }

    private TreeNode delete(TreeNode root, int key) {
        if (root == null) return null;

        if (root.val > key) {
            root.left = delete(root.left,key);
        } else if (root.val < key) {
            root.right = delete(root.right,key);
        } else {
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;
            TreeNode tmp = root.right;
            while (tmp.left != null) {
                tmp = tmp.left;
            }
            root.val = tmp.val;
            root.right = delete(root.right,tmp.val);
        }
        return root;
    }
}