首页 > 其他 > 详细

根节点路径问题

时间:2015-07-20 23:17:55      阅读:268      评论:0      收藏:0      [点我收藏+]

方法一:bottom-up

Node *LCA(Node *root, Node *p, Node *q) {
  if (!root) return NULL;
  if (root == p || root == q) return root;
  Node *left = LCA(root->left, p, q);
  Node *right = LCA(root->right, p, q);
  if (left && right) return root;  // if p and q are on both sides
  return left ? left :right ;  // either one of p,q is on one side OR p,q is not in L&R subtrees
}

方法二:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
     if(root==NULL||p==NULL||q==NULL)  return NULL;
    
     vector<TreeNode*>s1;
     vector<TreeNode*>s2;
     bool left=findpath(root,p,s1);
     bool right=findpath(root,q,s2);
     int i;
     if(left&&right){
        for( i=0;i<s1.size()&&i<s2.size();i++){
            if(s1[i]!=s2[i])  break;
        }
        return s1[i-1];
        
    }
    else return NULL;
        
    }
    bool  findpath(TreeNode*root,TreeNode*p,vector<TreeNode*>&s1){
        TreeNode*cur=root;
        TreeNode*prev=NULL;
        while(cur!=NULL||!s1.empty()){
            while(cur!=NULL){
                s1.push_back(cur);
                cur=cur->left;
                
            }
            cur=s1.back();
            if(cur->right==NULL||cur->right==prev){
                if(cur==p){
                    
                    return true;
                }
                prev=cur;
                cur=NULL;
                s1.pop_back();
            }
            else 
                cur=cur->right;
        }
        return false;
    }

方法三:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    
    if(root==NULL||p==NULL||q==NULL)  return NULL;
    
    vector<TreeNode*>s1;
    vector<TreeNode*>s2;
    bool left=findpath(root,p,s1);
    bool right=findpath(root,q,s2);
    int i;
    if(left&&right){
        for( i=0;i<s1.size()&&i<s2.size();i++){
            if(s1[i]!=s2[i])  break;
        }
        return s1[i-1];
        
    }
    else return NULL;
        
}
    
       bool findpath(TreeNode*root,TreeNode*p,vector<TreeNode*>&s){
        if(root==NULL)  return false;
        s.push_back(root);
        if(root==p) return true;
        bool left=findpath(root->left,p,s);
        bool right=findpath(root->right,p,s);
        if(left||right) return true;
        s.pop_back();
        return false;
        
        
    }

 

根节点路径问题

原文:http://www.cnblogs.com/kkshaq/p/4662840.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!