給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對于有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先)。”
例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]
示例
示例 1:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
輸出: 3
解釋: 節點 5 和節點 1 的最近公共祖先是節點 3。
示例 2:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
輸出: 5
解釋: 節點 5 和節點 4 的最近公共祖先是節點 5。因為根據定義最近公共祖先節點可以為節點本身。
解題思路:
1. 借助外部存儲
使用hash表記錄每個節點的父節點,遍歷p和q的父節點,第一個共同的節點即為最近公共祖先。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private Map<Integer,TreeNode> map = new HashMap<Integer,TreeNode>();
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//借助hash表存儲每個節點的父節點,然后向上遍歷是夠存在共同節點
if(root == null || root == p || root == q) return root;
//dfs遍歷,為每個節點添加父節點
dfs(root);
//set集合特點:無序、不重復
Set<TreeNode> set = new HashSet<TreeNode>();
//將節點p或者q的父節點存入set集合
while(p != null)
{
set.add(p);
p = map.get(p.val);
}
//查看q的父節點是否存在集合中
while(q != null)
{
if(set.contains(q))
{
return q;
}
q = map.get(q.val);
}
return null;
}
private void dfs(TreeNode root)
{
if(root.left != null)
{
map.put(root.left.val,root);
dfs(root.left);
}
if(root.right != null)
{
map.put(root.right.val,root);
dfs(root.right);
}
}
}
2.深度優先搜索
對二叉樹進行后序遍歷,查找p和q節點,向上回溯找到公共祖先。
遞歸解析:
明確邊界:
1.當越過葉子節點時,直接返回null
2.當節點root==p 或者q時,返回root
遞歸內容:
分別遞歸二叉樹的左右子節點,返回值標記為left和right
返回值:
當left和right均不為空時,返回root節點
當left和right均為空時,返回null
當left不為空,則返回left
當right不為空,返回right
實現:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//dfs
if(root == null) return null;
if(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;
if(left == null) return right;
if(right == null) return left;
return null;
}
}