题目描述
题目链接:236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
例子
例子 1
Input:
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3 Explanation: The LCA of nodes 5 and 1 is 3.
例子 2
Input:
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
例子 3
Input:
root = [1,2], p = 1, q = 2
Output: 1
Constraints
- The number of nodes in the tree is in the range
[2, 10^5]
.-10^9 <= Node.val <= 10^9
- All
Node.val
are unique.p != q
p
andq
will exist in the BST.
解题思路
这里涉及到在二叉树中对节点的搜索,思路如下:
- 对一棵树同时搜索
p
或者q
- 如果根结点是空,直接返回空指针
- 如果根结点是
p
或者q
,直接返回根结点(因为假如另一个节点在同一棵树内的话(题目保证了两个节点都会存在),最深的祖先节点一定是根结点) - 否则对左右两颗子树进行同样操作,得到返回结果
left
和right
- 假如
left
和right
都非空,表示在左子树和右子树都搜到了其中一个节点,此时根结点为最近祖先节点,返回根结点 - 假如
left
和right
只有一个非空节点,表示除了该非空节点的子树外,其他节点都不包含另一个节点,表明另一个节点一定在该节点的子树下,返回该节点作为最近祖先节点 - 假如
left
和right
都为节点:不可能,因为题目保证两个节点都存在
- 假如
代码如下:
/**
* 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) return nullptr;
if (root == p || root == q) return root;
// search node in left subtree
TreeNode* left_search = lowestCommonAncestor(root->left, p, q);
TreeNode* right_search = lowestCommonAncestor(root->right, p, q);
// we find node in both subtree
if (left_search && right_search) {
return root;
} else if (left_search) {
return left_search;
} else {
return right_search;
}
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(h) – 递归深度
GitHub 代码同步地址: 236.LowestCommonAncestorOfABinaryTree.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions