方法1:dfs
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode res;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
boolean flag = help(root, p, q);
return res;
}
public boolean help(TreeNode root, TreeNode p, TreeNode q){
if(root == null){
return false;
}
boolean left = help(root.left, p, q);
boolean right = help(root.right, p ,q);
if(left && right || (root==p && (left || right)) || (root==q &&(left || right))){ //如果当前节点的左子树和右子树分别存在p和q,p和q之一为当前节点,则当前节点为其最近祖先
res = root;
return true;
}
return root==p || root==q || left || right;
}
}
方法2:迭代保存父节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//迭代保存parent节点
Map<TreeNode, TreeNode> parents = new HashMap<>();
Set<TreeNode> visit = new HashSet<>();
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
dfs(root);
while(p!=null){
visit.add(p);
p = parents.get(p);
}
while(q!=null){
if(visit.contains(q)){
return q;
}
q = parents.get(q);
}
return null;
}
public void dfs(TreeNode root){
if(root == null){
return;
}
if(root.left != null){
parents.put(root.left, root);
dfs(root.left);
}
if(root.right != null){
parents.put(root.right, root);
dfs(root.right);
}
}
}