AcWing 88. 树中两个结点的最低公共祖先
原题链接
中等
作者:
我要出去乱说
,
2021-02-22 21:52:28
,
所有人可见
,
阅读 390
/**
* 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) return NULL; //递归到空节点,说明当前子树不包含p和q
if (root == p || root == q) return root; //递归找到p或q直接返回
auto left = lowestCommonAncestor(root->left, p, q);
auto right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root; //p,q分别在左右子树,则返回当前节点
if (left) return left; //p,q都在左子树,返回左节点
else return right;
}
};