Simple recursion solution


  • 0
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            // same side of root
            if (p.val > root.val && q.val > root.val) {
                // right
                TreeNode tmp = root.right;
                return lowestCommonAncestor(tmp, p, q);
            } else if (p.val < root.val && q.val < root.val) {
                // left
                TreeNode tmp = root.left;
                return lowestCommonAncestor(tmp, p, q);
            } else {
                // different side
                return root;
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.