这道题想用寻找路径的方法来解决,但是最后没能成功ac,看了一下别人的想法,自己又走弯路了!递归完全可以额!
public class ImportantLowestCommonAncestorofaBinaryTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null;
if (root == p || root == q)
return root;
TreeNode L = lowestCommonAncestor(root.left, p, q);
TreeNode R = lowestCommonAncestor(root.right, p, q);
if (L != null && R != null)
return root;
return L != null ? L : R;
}
}