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

    你可能感兴趣的文章
    OpenMV入门教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    OpenObserve云原生可观测平台本地Docker部署与远程访问实战教程
    查看>>
    OpenPPL PPQ量化(4):计算图的切分和调度 源码剖析
    查看>>
    OpenPPL PPQ量化(5):执行引擎 源码剖析
    查看>>
    openpyxl 模块的使用
    查看>>
    Openresty框架入门详解
    查看>>
    OpenResty(1):openresty介绍
    查看>>
    OpenResty(2):OpenResty开发环境搭建
    查看>>
    openshift搭建Istio企业级实战
    查看>>
    Openstack 之 网络设置静态IP地址
    查看>>
    OpenStack 综合服务详解
    查看>>
    OpenStack 网络服务Neutron详解
    查看>>
    Openstack(两控制节点+四计算节点)-1
    查看>>
    openstack--memecache
    查看>>
    openstack-keystone安装权限报错问题
    查看>>
    openstack【Kilo】汇总:包括20英文文档、各个组件新增功能及Kilo版部署
    查看>>
    openstack下service和endpoint
    查看>>
    Openstack企业级云计算实战第二、三期培训即将开始
    查看>>
    OpenStack创建虚拟机实例实战
    查看>>
    OpenStack安装部署实战
    查看>>