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

    你可能感兴趣的文章
    oracle零碎要点---oracle em的web访问地址忘了
    查看>>
    Oracle零碎要点---多表联合查询,收集数据库基本资料
    查看>>
    Oracle静默安装
    查看>>
    Oracle面试题:Oracle中truncate和delete的区别
    查看>>
    ThreadLocal线程内部存储类
    查看>>
    thinkphp 常用SQL执行语句总结
    查看>>
    Oracle:ORA-00911: 无效字符
    查看>>
    Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
    查看>>
    TCP基本入门-简单认识一下什么是TCP
    查看>>
    tableviewcell 中使用autolayout自适应高度
    查看>>
    Orcale表被锁
    查看>>
    svn访问报错500
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>