LeetCode刷题
由于业务需要,楼主需要将python代码同步转换为c++代码,所以为了更快学习与适应,决定通过刷题增加自己对于c++做题能力,并在这里记录下自己的相关思路与做法。
20240225-235.二叉搜索树的最近公共祖先
思路:
- 我们从根节点开始遍历,如果当前节点的值大于 p 和 q的值,说明 p和 q应该在当前节点的左子树,因此将当前节点移动到它的左子节点;
- 如果当前节点的值小于 p和 q的值,说明 p和 q应该在当前节点的右子树,因此将当前节点移动到它的右子节点;
- 如果当前节点的值不满足上述两条要求,那么说明当前节点就是「分岔点」。此时,p 和 q要么在当前节点的不同的子树中,要么其中一个就是当前节点。
时间复杂度:最坏情况就是将所有结点都遍历,直到剩下最后两个结点,所以时间复杂度为O(n)
空间复杂度:由于未使用任何额外存储,所以空间复杂度为O(1)
下面是给出的代码,并且包含了输入输出主函数,方便本地调试。
C++代码
/*
1、二叉搜索树的最近公共祖先
*/
#include <cstddef>
#include <iostream>
#include <string>
#include "common.h"
using namespace std;
class Solution{
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){
TreeNode* ancestor = root;
while (true)
{
if (p->val < ancestor->val && q->val < ancestor->val)
{
ancestor = ancestor->left;
}
else if (p->val > ancestor->val && q->val > ancestor->val)
{
ancestor = ancestor->right;
}
else{
break;
}
}
return ancestor;
}
};
int main(){
TreeNode* root = new TreeNode(10);
root->left = new TreeNode(5);
root->right = new TreeNode(15);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(7);
root->right->left = new TreeNode(12);
root->right->right = new TreeNode(18);
// 测试用例1:p 和 q 都在左子树中
TreeNode* p1 = root->left->left;
TreeNode* q1 = root->left->right;
TreeNode* result1 = Solution().lowestCommonAncestor(root, p1, q1);
cout << "Test case 1: " << result1->val << endl; // 预期输出:5
// 测试用例2:p 和 q 都在右子树中
TreeNode* p2 = root->right->left;
TreeNode* q2 = root->right->right;
TreeNode* result2 = Solution().lowestCommonAncestor(root, p2, q2);
cout << "Test case 2: " << result2->val << endl; // 预期输出:15
// 测试用例3:p 在左子树中,q 在右子树中
TreeNode* p3 = root->left->left;
TreeNode* q3 = root->right->right;
TreeNode* result3 = Solution().lowestCommonAncestor(root, p3, q3);
cout << "Test case 3: " << result3->val << endl; // 预期输出:10
// 释放内存
delete root;
return 0;
}