68-01 二叉树的最近公共祖先
题目
对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。
给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
C++ 题解
递归思想, 对以root为根的(子)树进行查找p和q, 如果root == null || p || q 直接返回root,表示对于当前树的查找已经完毕, 否则对左右子树进行查找, 根据左右子树的返回值判断:
- 左右子树的返回值都不为null, 由于值唯一左右子树的返回值就是p和q, 此时root为LCA
- 如果左右子树返回值只有一个不为null, 说明只有p和q存在与左或右子树中, 最先找到的那个节点为LCA
- 左右子树返回值均为null, p和q均不在树中, 返回null
/**
* 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 == nullptr && right == nullptr)
return nullptr;
else if(left != nullptr && right != nullptr)
return root;
else
{
return left == nullptr ? right : left;
}
}
};
python 题解
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == None or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if left == None and right == None:
return None
elif left != None and right !=None:
return root
else:
if right:
return right
if left:
return left