Binary Tree的问题,首先要考虑使用递归的思想:如果当前的结点为空或为目标结点之一,那么就直接返回当前结点,接下来递归地在左右子树中寻找目标结点,如果两个目标结点分别在root的两侧,那么root就是它们的lowest common ancestor;如果left为空,那么说明两个目标结点都在right子树中,返回right;反之则返回left。代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null) return root;
return left != null? left : right;
}
}
第二种方法是迭代,比较容易理解,分别记录p和q结点之前(包括p和q)的每个节点的parent,然后我们使用一个Set存储p结点的所有parent,然后逐步寻找q结点的所有parent,如果Set里面已经有这个元素,那么就直接返回。代码如下:
public class Solution{
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
Map<TreeNode, TreeNode> parent = new HashMap<>();
Stack<TreeNode> stack = new Stack<>();
parent.put(root, null);
stack.push(root);
while(!parent.containsKey(p) || !parent.containsKey(q)){
TreeNode node = stack.pop();
if(node.left != null){
parent.put(node.left, node);
stack.push(node.left);
}
if(node.right != null){
parent.put(node.right, node);
stack.push(node.right);
}
}
Set<TreeNode> ancestors = new HashSet<>();
while(p != null){
ancestors.add(p);
p = parent.get(p);
}
while(!ancestors.contains(q)){
q = parent.get(q);
}
return q;
}
}
知识点:
1. 注意第二种迭代法中寻找每个node parent结点的方法