1 line solution - java


  • 7
    A

    If both p and q in same direction (less or greater than), then change the root to its child in that direction. otherwise for all other cases it has to be the root.

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

  • 0
    A

    downvoted ? is there something wrong with this approach or thinking ?


  • 0
    F

    I personally think it's neat, but I imagine this method is frowned upon in team environment.


Log in to reply
 

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