树中两个结点的最低公共祖先-68
给出一个二叉树,输入两个树节点,求它们的最低公共祖先。
一个树节点的祖先节点包括它本身。
注意:
- 输入的二叉树不为空;
- 输入的两个节点一定不为空,且是二叉树中的节点;
样例
二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]如下图所示:
8
/ \
12 2
/ \
6 4
1. 如果输入的树节点为2和12,则输出的最低公共祖先为树节点8。
2. 如果输入的树节点为2和6,则输出的最低公共祖先为树节点2。
思路:
如果树是二叉搜索树,可以利用BST的特性。
递归:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val > root.val && q.val > root.val)
return lowestCommonAncestor(root.right, p, q);
else if (p.val < root.val && q.val < root.val)
return lowestCommonAncestor(root.left, p, q);
else return root;
}
}
迭代:
class Solution {
public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
while (root != null) {
if (p.val > root.val && q.val > root.val)
root = root.right;
else if (p.val < root.val && q.val < root.val)
root = root.left;
else return root;
}
return null;
}
}
若是普通的二叉树
注意 p,q 必然存在树内, 且所有节点的值唯一!!!
递归思想,对以 root 为根的(子)树进行查找 p 和 q ,如果 root == null || p || q 直接返回 root
表示对于当前树的查找已经完毕,否则对左右子树进行查找, 根据左右子树的返回值判断
- 左右子树的返回值都不为null, 由于值唯一左右子树的返回值就是p和q, 此时root为LCA;
- 果左右子树返回值只有一个不为null, 说明只有p或q存在于左或右子树中, 最先找到的那个节点为LCA;
- 左右子树返回值均为null, p和q均不在树中, 返回null;
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 null;
else if (left != null && right != null) return root;
else return left == null ? right : left;
}
}