Recursive Java solution.


  • 0
    O
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            TreeNode result;
            if (p.val < root.val && q.val < root.val) {
                result = lowestCommonAncestor(root.left, p, q);
            } else if(p.val > root.val && q.val > root.val) {
                result = lowestCommonAncestor(root.right, p, q);
            } else {
                result = root;
            }
            return result;
        }
    }
    

Log in to reply
 

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