1、题目描述:
2、题解:
方法:深度优先搜索 ,后序遍历
祖先的定义: 若节点 p 在节点 root 的左(右)子树中,或 p = root ,则称 root是 p 的祖先。
最近公共祖先的定义: 设节点 root 为节点 p, q的某公共祖先,若其左子节点 root.left 和右子节点 root.right都不是 p,q的公共祖先,则称 root是 “最近的公共祖先” 。
可以发现后序遍历,第一个找到的点就是最近的公共祖先。
有以下三种情况:
1、p和q在root的子树中,且分别是root的异侧
2、p = root,q在root的子树中
3、q = root,p在root的子树中
Python代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
#DFS后序遍历
if not root:
return None
if 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: #说明p和q都不在root中
return None
if not left:#说明在p和q只有一个存在以root为根的树中
return right
if not right :#说明在p和q只有一个存在以root为根的树中
return left
return root #p,q都在以root为根的树中
C++代码:
/**
* 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 (not root || root == p || root == q) return root ;
TreeNode* left = lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if (not left && not right) return NULL ;
if (not left) return right;
if (not right) return left;
return root;
}
};
3、复杂度分析:
时间复杂度:O(N),N为二叉树的结点数,最差情况下要遍历所有节点
空间复杂度:O(N)