/**
* 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;
if (p->val > root->val && q->val < root->val || p->val < root->val && q->val > root->val)
return root;
if (p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right, p, q);
else
return lowestCommonAncestor(root->left, p, q);
}
};
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先 C++ 2021-08-20
最新推荐文章于 2022-10-19 21:06:01 发布