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

    你可能感兴趣的文章
    pandas 数据帧多行查询
    查看>>
    pandas 数据框将 INT64 列转换为布尔值
    查看>>
    pandas 数据框将列类型转换为字符串或分类
    查看>>
    pandas 数据框条件 .mean() 取决于特定列中的值
    查看>>
    pandas 数据框至海运分组条形图
    查看>>
    Pandas 数据透视表:列顺序和小计
    查看>>
    pandas 时序统计的高级用法!
    查看>>
    pandas 时间序列重新采样结束给定的一天
    查看>>
    pandas 根据不是常量的第三列的值将值从一列复制到另一列
    查看>>
    pandas 根据值从多列中的一列查找
    查看>>
    Pandas 根据布尔条件选择行和列
    查看>>
    pandas 滚动窗口 - datetime64[ns] 未实现
    查看>>
    pandas 版本兼容特定的蟒蛇和NumPy配置吗?
    查看>>
    pandas 生成excel多级表头
    查看>>
    Pandas 的 DataFrame 详解-ChatGPT4o作答
    查看>>
    pandas 读取excel数据,以字典形式输出
    查看>>
    Pandas 读取具有浮点值的 csv 文件会导致奇怪的舍入和小数位数
    查看>>
    pandas 适用,但仅适用于满足条件的行
    查看>>
    pandas 重新采样到每月的特定工作日
    查看>>
    pandas :我如何对堆叠的条形图进行分组?
    查看>>