很巧妙的运用了递归的方法
/** * 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 ans=null;
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
search(root,p,q);
return ans;
}
public bool search(TreeNode boot,TreeNode a,TreeNode b) {
if(boot==null)
return false;
bool lson=search(boot.left,a,b);
bool rson=search(boot.right,a,b);
if((lson&&rson)||((boot.val==a.val||boot.val==b.val)&&(lson||rson)))
ans=boot;
return lson||rson||boot.val==a.val||boot.val==b.val;
}
}