标签:node sel blank 应该 null data self function else
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
        _______3______
       /                  ___5__          ___1__
   /      \        /         6      _2       0       8
         /           7   4
5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition./**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode node = null;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        findNode(root, p, q);
        return node;
    }
    public int findNode(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return 0;
        }
        int re = 0;
        if (root == p) {
            re = 1 + findNode(root.left, p, q) + findNode(root.right, p, q);
        } else if (root == q) {
            re = 2 + findNode(root.left, p, q) + findNode(root.right, p, q);
        } else {
            int left = findNode(root.left, p, q);
            if (left == 3) {
                return 3;
            }
            int right = findNode(root.right, p, q);
            if (right == 3) {
                return 3;
            }
            re = left + right;    
        }
        if (re == 3) {
            node = root;
        }
        return re;
    }
}
recursively root,检查root是否是pq,root的左子树是否有pq,root的右子树是否有pq。 18%
**这种办法是基于p、q一定在root中
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null) return null;
        if(root==p || root==q) return root;
        TreeNode left=lowestCommonAncestor(root.left, p, q), right = lowestCommonAncestor(root.right, p, q);
        if(left!=null && right!=null) return root;
        if(right==null) return left;
        if(left==null) return right;
        return null;
    }
}
236. Lowest Common Ancestor of a Binary Tree
标签:node sel blank 应该 null data self function else
原文地址:http://www.cnblogs.com/yuchenkit/p/7192628.html