题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
解析
最简单的想法就是把根到该节点的搜索路径存储下来然后两个路径反向比较即可。
class Solution {
public boolean found = false; // 标志位,表示是否已找到目标
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
List<TreeNode> list1 = new ArrayList<>();
List<TreeNode> list2 = new ArrayList<>();
DFS(root, p.val, list1);
found = false;
DFS(root, q.val, list2);
for(int i = Math.min(list1.size(), list2.size()) - 1; i >= 0; i--){
if(list1.get(i).equals(list2.get(i))){
return list1.get(i);
}
}
return null;
}
public void DFS(TreeNode node, int val, List<TreeNode> list){
if(node == null || found) {
return;
}
list.add(node);
if (node.val == val) {
found = true;
return;
}
DFS(node.left, val, list);
if (!found) {
DFS(node.right, val, list);
}
if (!found) {
list.remove(list.size() - 1);
}
}
}
是实际上可以在递归中,找左右子树中是否有符合条件的节点,如果在左右子树中都找到,说明该节点是公共祖先节点,如果左子树不为空,右子树为空,说明如果存在公共祖先节点一定是在左子树中,同理,反之则在右子树中,则进而在对应子树中寻找。
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;
}
}

629

被折叠的 条评论
为什么被折叠?



