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 };
  • 相关阅读:
    2019 SDN上机第7次作业
    第01组 Beta冲刺(4/5)
    第01组 Beta冲刺(3/5)
    第01组 Beta冲刺(2/5)
    第01组 Beta冲刺(1/5)
    2019 SDN上机第6次作业
    2019 SDN上机第5次作业
    SDN课程阅读作业(2)
    第01组 Alpha事后诸葛亮
    第01组 Alpha冲刺(6/6)
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14230696.html
Copyright © 2011-2022 走看看