题目链接:
https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/
对于每个结点讨论四种情况:
1.左子树不存在结点为nullptr,以 left来标记。右子树不存在结点为nullptr,以right来标记。那么返回nullptr。
2.left和right均不为空,返回当前结点
3.left为空,而right不会空,细分两种情况:
(1)一个结点在右子树,则right指向p或q。
(2)两个结点在右子树中,则right指向两个结点的最低公共
直接返回right
4.right为空,left不为空情况类似3
/**
* 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)return right;
if(!right)return left;
return root;
}
};