LintCode-剑指Offer-(88)最近公共祖先

来源:互联网 发布:网络安全法考试单选 编辑:程序博客网 时间:2024/06/05 09:45
class Solution {public:    /**    * @param root: The root of the binary search tree.    * @param A and B: two nodes in a Binary.    * @return: Return the least common ancestor(LCA) of the two nodes.    */    TreeNode *lowestCommonAncestor(TreeNode *root,TreeNode *A,TreeNode *B) {        // write your code here        if (root==NULL)return NULL;        if (root->left==NULL&&root->right==NULL)return root;        vector<TreeNode*>vta = getlist(root,A);        vector<TreeNode*>vtb = getlist(root,B);        int i = 0;        while (i<vta.size()&&i<vtb.size()&&vta[i]==vtb[i]){            i++;        }        if (i==vta.size()&&i<vtb.size())return A;        if (i<vta.size()&&i==vtb.size())return B;        return vta[i-1];    }    vector<TreeNode*> getlist(TreeNode* root,TreeNode* A){        vector<TreeNode*> vta;        while (root!=A){            vta.push_back(root);            if (IsChild(root->left,A)==true){                root = root->left;            }            else if (IsChild(root->right,A)==true){                root = root->right;            }        }        return vta;    }    bool IsChild(TreeNode* root,TreeNode* a){        if (root==NULL)return false;        if (root==a)return true;        return IsChild(root->left,a)|IsChild(root->right,a);    }};
0 0
原创粉丝点击