面试题 04.08. 首个共同祖先
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-common-ancestor-lcci/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目分析
/**
* 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;
//
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left && right) return root;
return left ? left : right;
}
};