lc235.二叉搜尋樹的最近公共祖先【①分別得到祖先序列,然後比較;②***同時查詢,找出分岔結點】

三塊桌布發表於2020-09-27

①分別得到祖先序列,然後比較

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector<TreeNode*> pathp=search(root,p);
        vector<TreeNode*> pathq=search(root,q);
        TreeNode* re;
        int i;
        for(i=0; i<pathp.size()&&i<pathq.size(); ++i){
            if(pathp[i]==pathq[i]) re=pathp[i];
            else break;
        }
        return re;
    }
    vector<TreeNode*> search(TreeNode* &root,TreeNode* &p){
        vector<TreeNode*> path;
        TreeNode* node=root;
        while(node!=p && node){
            path.push_back(node);
            if(p->val < node->val){
                node=node->left;
            }else{
                node=node->right;
            }
        }
        path.push_back(node);
        return path;
    }
};

②***同時查詢,找出分岔結點

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* node=root;
        while(1){
            if(p->val<node->val && q->val<node->val){
                node=node->left;
            }else if(p->val>node->val && q->val>node->val){
                node=node->right;
            }else break;
        }
        return node;
    }
};

 

相關文章