剑指 Offer 68 - II. 二叉树的最近公共祖先
题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
解题思路
- 终止条件:
- 当越过叶节点,则直接返回
nullptr
- 当
root
等于p
或者q
,则直接返回root
- 当越过叶节点,则直接返回
- 递推工作:
- 开启递归左子节点,返回值记为
left
- 开启递归右子节点,返回值记为
right
- 开启递归左子节点,返回值记为
- 返回值,根据
left
和right
,可展开为四种情况- 当
left
和right
同时为空,说明root
的左 / 右子树中都不包含p
或q
,返回nullptr
- 当
left
和right
同时不为空,说明p
和q
分列在root
的异侧(分别在左/右子树),因此root
为最近公共祖先,返回root
- 当
left
为空,right
不为空,有两种情况p
、q
其中一个在右子树中,此时right
指向p
或q
p
、q
都在右子树中,此时right
指向最近公共祖先即诶单
- 当
left
不为空、right
为空,同理
- 当
复杂度分析
时间复杂度:O(N)
空间复杂度:O(N)
知识点
二叉树,递归,DFS
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), 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 && !right) {
return nullptr;
}
if(left == nullptr) return right;
if(right == nullptr) return left;
return root;
}
};