sword_for_offer/docs/剑指 Offer 68 - II. 二叉树的最近公共祖先.md
祖先的定义: 若节点 $p$ 在节点 $root$ 的左(右)子树中,或 $p = root$ ,则称 $root$ 是 $p$ 的祖先。
最近公共祖先的定义: 设节点 $root$ 为节点 $p, q$ 的某公共祖先,若其左子节点 $root.left$ 和右子节点 $root.right$ 都不是 $p,q$ 的公共祖先,则称 $root$ 是 “最近的公共祖先” 。
{:width=450}
根据以上定义,若 $root$ 是 $p, q$ 的 最近公共祖先 ,则只可能为以下情况之一:
{:width=450}
考虑通过递归对二叉树进行先序遍历,当遇到节点 $p$ 或 $q$ 时返回。从底至顶回溯,当节点 $p, q$ 在节点 $root$ 的异侧时,节点 $root$ 即为最近公共祖先,则向上返回 $root$ 。
3. 同理;观察发现, 情况
1.可合并至3.和4.内,详见文章末尾代码。
<,,,,,,,,,,,,,,,,,>
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root == p or root == q: return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not left: return right
if not right: return left
return root
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) return right;
if(right == null) return left;
return root;
}
}
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr) return right;
if(right == nullptr) return left;
return root;
}
};
情况 1. , 2. , 3. , 4. 的展开写法如下。
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root == p or root == q: return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not left and not right: return # 1.
if not left: return right # 3.
if not right: return left # 4.
return root # 2. if left and right:
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; // 1.
if(left == null) return right; // 3.
if(right == null) return left; // 4.
return root; // 2. if(left != null and right != null)
}
}
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr && right == nullptr) return nullptr; // 1.
if(left == nullptr) return right; // 3.
if(right == nullptr) return left; // 4.
return root; // 2. if(left != null and right != null)
}
};