• Leetcode 235 Lowest Common Ancestor of a Binary Search Tree 二叉树


        给定一个二叉搜索树的两个节点,找出他们的最近公共祖先,如,

            _______6______
           /              
        ___2__          ___8__
       /              /      
      0        4       7       9
              /  
             3    5

    2和8的最近公共祖先是6,2和4的最近公共祖先是2,假设找的3和5

    TreeNode* l =lowestCommonAncestor(root->left,p,q) ;
    TreeNode* r =lowestCommonAncestor(root->right,p,q) ;

    返回到4时两个都不是Nullptr,那么要返回4的指针 即if(l && r ) return root;
    返回到2时只有r是Nullptr,那么要返回4的指针 即else if(!l && r) return r;
    返回到6时只有l是Nullptr,那么要返回4的指针 即else if(l && !r) return l;
    返回到8时都是是Nullptr,那么返回NULL 即else return NULL;

    本文的求解方法没有利用二叉搜索树的特点,因此效率较低

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    13         if(!root) return NULL;
    14         else if(!q&&!p){
    15             return NULL;
    16         }
    17         else if(root->val == p->val){
    18             return root;
    19         }
    20         else if(q->val == root->val){
    21             return root;
    22         }
    23         else {
    24             TreeNode* l =lowestCommonAncestor(root->left,p,q) ;
    25             TreeNode* r =lowestCommonAncestor(root->right,p,q) ;
    26             if(l && r ) return root;
    27             else if(!l && r) return r;
    28             else if(l && !r) return l;
    29             else return NULL;
    30         }
    31     }
    32 };
  • 相关阅读:
    TVM性能评估分析(三)
    TVM性能评估分析(二)
    TVM性能评估分析(一)
    飞腾上实体名单?
    华为不造车,广汽合作智能驾驶
    异构计算编程
    服务器硬件层次架构
    为何说要多用组合少用继承?如何决定该用组合还是继承?
    极客时间学习
    如果学不好编程,就看看这个吧
  • 原文地址:https://www.cnblogs.com/onlyac/p/5156307.html
Copyright © 2020-2023  润新知