博客
关于我
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/

    你可能感兴趣的文章
    Netpas:不一样的SD-WAN+ 保障网络通讯品质
    查看>>
    netty底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
    查看>>
    Netty核心模块组件
    查看>>
    Netty源码—4.客户端接入流程一
    查看>>
    Netty源码—7.ByteBuf原理四
    查看>>
    Nginx 学习总结(17)—— 8 个免费开源 Nginx 管理系统,轻松管理 Nginx 站点配置
    查看>>
    Objective-C实现bellman-ford贝尔曼-福特算法(附完整源码)
    查看>>
    Objective-C实现BellmanFord贝尔曼-福特算法(附完整源码)
    查看>>
    Objective-C实现binary exponentiation二进制幂运算算法(附完整源码)
    查看>>
    Objective-C实现binomial coefficient二项式系数算法(附完整源码)
    查看>>
    Objective-C实现hardy ramanujana定理算法(附完整源码)
    查看>>
    Objective-C实现insertion sort插入排序算法(附完整源码)
    查看>>
    Objective-C实现Interpolation search插值查找算法(附完整源码)
    查看>>
    Objective-C实现k nearest neighbours k最近邻分类算法(附完整源码)
    查看>>
    Objective-C实现k-nearest算法(附完整源码)
    查看>>
    Objective-C实现KPCA(附完整源码)
    查看>>
    Objective-C实现max subarray sum最大子数组和算法(附完整源码)
    查看>>
    Objective-C实现MaximumSubarray最大子阵列(动态规划解决方案)算法(附完整源码)
    查看>>
    Objective-C实现md5算法(附完整源码)
    查看>>
    Objective-C实现miller rabin米勒-拉宾素性检验算法(附完整源码)
    查看>>