/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode result = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)
return null;
if(isLCA(root, p, q))
return result;
return null;
}
public boolean isLCA(TreeNode root, TreeNode p, TreeNode q){
if(root == null)
return false;
int isLeft = isLCA(root.left, p, q) ? 1 : 0;
int isRight = isLCA(root.right, p, q) ? 1 : 0;
int isP = root == p ? 1 : 0;
int isQ = root == q ? 1 : 0;
if(isLeft + isRight + isP + isQ >= 2)
result = root;//LCA必须满足其中的两个条件
return isLeft + isRight + isP + isQ >= 1;//只要满足一个条件就返回true
}
}
这道题比想象的麻烦一点