博客
关于我
OJ-leetcode-235. 二叉搜索树的最近公共祖先(简单二叉搜索树)
阅读量:147 次
发布时间:2019-02-26

本文共 1826 字,大约阅读时间需要 6 分钟。

???????????????????????????????????????????????????????????????

????

??????????????????

  • ???????????????????????????????????????????????????
  • ???????????????????????????????????????????????
  • ????

    #include 
    using namespace std;class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector
    path_p = getPath(root, p); vector
    path_q = getPath(root, q); return findLastCommonAncestor(path_p, path_q); } vector
    getPath(TreeNode* node, TreeNode* target) { vector
    path; while (node != null && node != target) { path.push_back(node); if (node->left != null && node->left->val == target->val) { node = node->left; } else if (node->right != null && node->right->val == target->val) { node = node->right; } else { return path; } } if (node != null) { path.push_back(node); } return path; } TreeNode* findLastCommonAncestor(const vector
    & path_p, const vector
    & path_q) { int i = 0, j = 0; int len = 0; TreeNode* last = null; while (i < path_p.size() && j < path_q.size()) { if (path_p[i]->val == path_q[j]->val) { if (last != path_p[i]) { last = path_p[i]; } len++; i++; j++; } else { if (i < j) { i++; } else { j++; } } } return last; }};

    ????

  • lowestCommonAncestor??????????getPath??????????????????findLastCommonAncestor??????????????????????????????????????
  • getPath??????????????????????????????????????????
  • findLastCommonAncestor???????????????????????????????????????????????
  • ????????????O(h)?????????????????h??????

    转载地址:http://hztf.baihongyu.com/

    你可能感兴趣的文章
    PL/SQL提示“ORA-01722:无效数字,将无效数字查找出来
    查看>>
    PL/sql语法单元
    查看>>
    PL/SQL连接远程服务器数据库,出现ORA-12154: TNS: 无法解析指定的连接标识符。
    查看>>
    pl/sql锁
    查看>>
    PL2303 Windows 10 驱动项目常见问题解决方案
    查看>>
    QueryPerformanceCounter与QueryPerformanceFrequency
    查看>>
    Plaid.com的监控系统如何实现与9600多家金融机构的集成
    查看>>
    Plain Stock Prediction:基于RNN的股票价格预测工具
    查看>>
    platform_driver与file_operations两种方法开发led驱动
    查看>>
    PlatON共识方案详解:应用CBFT共识协议,提高共识效率
    查看>>
    QueryDict和模型表知识补充
    查看>>
    Querybase 使用与安装教程
    查看>>
    Playwright与Selenium的对比:谁是更适合你的自动化测试工具?
    查看>>
    quarz设置定时器任务的有效时间段_定时器?你知道有几种实现方式吗?
    查看>>
    PLC、DCS、SCADA的选型
    查看>>
    PLC中的电子凸轮的简单介绍
    查看>>
    PLC发展详解-ChatGPT4o作答+匹尔西
    查看>>
    PLC探针有什么用
    查看>>
    PLC接线详解
    查看>>
    PLC数组的使用(西门子)
    查看>>