Accepted clean Java code with explanation


  • 0
      public class Solution {
        
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
          if (root == null)
            return null;
          
          // both p and q are less than root
          // their ancestor must be in root.left
          if (p.val < root.val && q.val < root.val)
            return lowestCommonAncestor(root.left, p, q);
              
          // both p and q are greater than root
          // their ancestor must be in root.right
          if (p.val > root.val && q.val > root.val)
            return lowestCommonAncestor(root.right, p, q);
              
          return root;
        }
    
      }

Log in to reply
 

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