Lowest Common Ancestor III
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: The root of the binary tree.
* @param A: A TreeNode
* @param B: A TreeNode
* @return: Return the LCA of the two nodes.
*/
public boolean foundA = false, foundB = false;
public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
TreeNode res = helper(root,A,B);
if(foundA && foundB){
return res;
}else{
return null;
}
}
public TreeNode helper(TreeNode root, TreeNode A, TreeNode B){
if(root == null){
return root;
}
//先分派 再检查 不然结果会出错
TreeNode left = helper(root.left,A,B);
TreeNode right = helper(root.right,A,B);
if(root == A|| root == B){
//如果不或foundA, 当找到A后 遍历别的点时,如果root != //A,将会改变foundA的值
foundA = (root == A )|| foundA;
foundB = (root == B) ||foundB;
return root;
}
if(left != null && right != null){
return root;
}
else if(left != null){
return left;
}
else if(right != null){
return right;
}
return null;
}
}Last updated