• 【打卡】牛客网:BM37 二叉搜索树的最近公共祖先


    自己写的:

    感觉写的很工整。

    1. /**
    2. * struct TreeNode {
    3. * int val;
    4. * struct TreeNode *left;
    5. * struct TreeNode *right;
    6. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    7. * };
    8. */
    9. class Solution {
    10. public:
    11. /**
    12. * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    13. *
    14. *
    15. * @param root TreeNode类
    16. * @param p int整型
    17. * @param q int整型
    18. * @return int整型
    19. */
    20. int lowestCommonAncestor(TreeNode* root, int p, int q) {
    21. // write code here
    22. if(p > q){
    23. int temp = p;
    24. p = q;
    25. q = temp;
    26. }
    27. if(p <= root->val && q >= root->val) // p、q是不同节点
    28. return root->val;
    29. else if (q < root->val)
    30. return lowestCommonAncestor(root->left, p ,q);
    31. else
    32. return lowestCommonAncestor(root->right, p ,q);
    33. }
    34. };

    模板的:

    空间复杂度增加。用到了“记录搜索的路径”的方法,这可能是以后针对复杂问题也能用的、比较常用的模板吧。

    1. /**
    2. * struct TreeNode {
    3. * int val;
    4. * struct TreeNode *left;
    5. * struct TreeNode *right;
    6. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    7. * };
    8. */
    9. class Solution {
    10. public:
    11. /**
    12. * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    13. *
    14. *
    15. * @param root TreeNode类
    16. * @param p int整型
    17. * @param q int整型
    18. * @return int整型
    19. */
    20. vector<int> getPath(TreeNode* root, int target){
    21. vector<int> path;
    22. while(root->val != target){
    23. path.push_back(root->val);
    24. if(root->val < target)
    25. root = root->right;
    26. else
    27. root = root->left;
    28. }
    29. path.push_back(root->val);
    30. return path;
    31. }
    32. int lowestCommonAncestor(TreeNode* root, int p, int q) {
    33. // write code here
    34. vector<int> path1 = getPath(root, p);
    35. vector<int> path2 = getPath(root, q);
    36. int res;
    37. for(int i = 0; i < path1.size() && i < path2.size(); i++){
    38. if(path1[i] == path2[i])
    39. res = path1[i];
    40. else
    41. break;
    42. }
    43. return res;
    44. }
    45. };

  • 相关阅读:
    MES生产管理系统,你真的需要吗?
    【nlp】2.5(gpu version)人名分类器实战项目(对比RNN、LSTM、GRU模型)工程管理方式
    2024年新版宝塔面板如何安装WordPress网站教程
    zoneinfo
    npm切换淘宝镜像后报错的解决办法
    hithesis部署和VSCode远程编辑tex文件
    P高阶_(pandas入门)
    python实现某音自动登录+获取视频数据
    在Qt中解决opencv的putText函数无法绘制中文的一种解决方法
    2309亚当arsd的11.1版本
  • 原文地址:https://blog.csdn.net/weixin_47173826/article/details/134283700