BiruLyu
5/30/2017 - 6:45 PM

236. Lowest Common Ancestor of a Binary Tree.java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 /*
 func LCA
   if root in (None, p, q) return root
   left = LCA(root.left, p, q)
   right = LCA(root.right, p, q)
   return root if left and right else left or right
   
   被发现的p或者q会被不断地向上传递,如果某个节点的左子树有p,右子树有q,则这个节点则为LCA
 */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        
        if (root == null || root == p || root == q) return root;
        
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        
        if(left != null && right != null) {
            return root;
        } else if (left != null){
            return left;
        } else if (right != null){
            return right;
        } else {
            return null;
        }
    }
}