1、题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
2、方法
1)父节点存储法
(1)构造一个函数,把所有节点的父节点都存入哈希表中,键值:<Integer, TreeNode>;
(2)依次访问节点 p 的所有祖先节点,并设置一个集合 visited,存放节点 p 的所有祖先节点;
(3)依次访问节点 q 的所有祖先节点,并判断集合 visited 中是否存在,若存在,即为最近公共祖先节点,返回即可;否则,返回 null。
Map<Integer, TreeNode> parentMap = new HashMap<Integer, TreeNode>();
Set<Integer> visited = new HashSet<Integer>();
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
nodeOfParent(root);
while(p != null) {
visited.add(p.val);
p = parentMap.get(p.val);
}
while(q != null) {
if(visited.contains(q.val)) {
return q;
}
q = parentMap.get(q.val);
}
return null;
}
public void nodeOfParent(TreeNode root) {
if(root.left != null) {
parentMap.put(root.left.val, root);
nodeOfParent(root.left);
}
if(root.right != null) {
parentMap.put(root.right.val, root);
nodeOfParent(root.right);
}
}