二叉树的最近公共祖先
解题思路:
递归。从根节点开始,直到为null或找到等于其中一个再返回,否则去找它的左右子节点,再判断,如果两边返回的都不是null,就返回root,否则返回非空的一边返回的值。
代码:
/** * Definition for a binary tree node.
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{ val = x; }
} */
public class Solution
{
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
if(root==null||root.val==p.val||root.val==q.val)
return root;
TreeNode left=LowestCommonAncestor(root.left,p,q);
TreeNode right=LowestCommonAncestor(root.right,p,q);
if(left!=null&&right!=null)
return root;
else
return left==null?right:left;
}
}