题目信息
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 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。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例 2:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
说明:
- 所有节点的值都是唯一的。
- p、q 为不同节点且均存在于给定的二叉树中。
解法一、寻找目标节点路径,两个节点路径最后一个相同的节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
List<TreeNode> pPath = new ArrayList<>();
List<TreeNode> qPath = new ArrayList<>();
findPath(root, p, pPath);
findPath(root, q, qPath);
TreeNode result = root;
int i = pPath.size() - 1;
int j = qPath.size() - 1;
while (i >= 0 && j >= 0) {
if (pPath.get(i) != qPath.get(j)) {
break;
}
i--;
j--;
}
if (i < pPath.size() - 1) {
return pPath.get(i+1);
}
return result;
}
// 获取从根节点到目标节点的路径信息
private boolean findPath(TreeNode root, TreeNode target, List<TreeNode> path) {
// 如果当前节点是null,说明树中没有要找的节点
if (root == null) {
return false;
}
// 找到目标节点
if (root.val == target.val) {
path.add(root); // 如果另一个节点是其子节点,所以需要把目标节点叶放入路径中
return true;
}
// 搜索左子树,如果找到,则加入路径中
if (findPath(root.left, target, path)) {
path.add(root);
return true;
}
// 搜索右子树,如果找到,则加入路径中
if (findPath(root.right, target, path)) {
path.add(root);
return true;
}
return false;
}
}
解法二、直接找,p和q必然同属于一个子树中
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
// 从root的左子树寻找
TreeNode left = lowestCommonAncestor(root.left, p, q);
// 从root的右子树寻找
TreeNode right = lowestCommonAncestor(root.right, p, q);
// 如果左子树没有找到,则说明p和q都在右子树,则返回右子树的结果
// 如果左子树找到了,并且右子树没有找到,则说明p和q都在左子树,返回左子树的结果
// 如果左子树找到了,右子树也找到了,则说明两侧各有一个目标节点,返回root
return left == null ? right : (right == null ? left : root);
}
}