zoukankan      html  css  js  c++  java
  • LeetCode235.二叉搜索树的最近公共祖先

    题目

     1 class Solution {
     2 public:
     3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
     4         if((p->val - root->val) * (q->val - root->val)<0) return root;
     5         //if(root == p ) return p;
     6         //if(root == q) return q;
     7         if(p->val < root->val && q->val < root->val) return lowestCommonAncestor(root->left,p,q);
     8         if(p->val > root->val && q->val > root->val) return lowestCommonAncestor(root->right,p,q);
     9         return root;
    10     }
    11 };

    官方答案,学习

     1 class Solution {
     2 public:
     3     vector<TreeNode*> getPath(TreeNode* root,TreeNode* target){
     4         vector<TreeNode*>path;
     5         TreeNode* node = root;
     6         while(node!=target){
     7             path.push_back(node);
     8             if(target->val > node->val) node = node->right;
     9             else node = node->left;
    10         }
    11         path.push_back(node);
    12         return path;
    13     }
    14     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    15         vector<TreeNode*>path_p = getPath(root,p);
    16         vector<TreeNode*>path_q = getPath(root,q);
    17         TreeNode* ancestor;
    18         for(int i = 0;i < path_p.size() && i < path_q.size();i++){
    19             if(path_p[i] == path_q[i]) ancestor = path_p[i];
    20             else break;
    21         }
    22         return ancestor;
    23 
    24     }
    25 };
  • 相关阅读:
    python流程控制
    数据类型
    python之初接触
    使用 HttpWebRequest 向网站提交数据
    在 ASP.NET MVC4 中使用 NInject
    第一篇 微信商城 开发前的准备工作
    (一)模块基础
    函数之递归、匿名函数及内置方法
    装饰器的使用原理
    mybatis返回list
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14230696.html
Copyright © 2011-2022 走看看