236. Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:茉莉茶软化宫颈 知乎 编辑:程序博客网 时间:2024/06/11 04:29

超时了,amazing,主要是存储路径耗费大量的时间,要是能倒着走就好了。

/** * 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:    void func(TreeNode* root, TreeNode* p, TreeNode* q,vector<TreeNode*>& resultP,vector<TreeNode*>& resultQ,vector<TreeNode*>& temp)    {        if(root==NULL)            return;        else         {            temp.push_back(root);            if(resultP.size()==0&&root==p)                resultP=temp;            if(resultQ.size()==0&&root==q)                resultQ=temp;            if(resultP.size()!=0&&resultQ.size()!=0)                return;            if(root->left!=NULL)                func(root->left,p, q,resultP,resultQ,temp);            if(root->right!=NULL)                func(root->right,p, q,resultP,resultQ,temp);            temp.pop_back();        }    }    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {        vector<TreeNode*> resultP;        vector<TreeNode*> resultQ;        vector<TreeNode*> temp;        func(root,p,q,resultP,resultQ,temp);        int index=0;        while(index<min(resultP.size(),resultQ.size()))        {            if(resultP[index]==resultQ[index])                index++;            else                break;        }        return resultP[index--];    }};

后来试着另一种方式,只是保存其深度和值,最后再找,但是如果保存int,最多支持32层。。。。之后就越界了。。。尴尬。
参考了discuss,照着它的例子写出来类似的代码,amazing,厉害了我的哥。。。

/** * 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) {        if(root==NULL||root==p||root==q)            return root;        TreeNode* left=lowestCommonAncestor(root->left, p, q);        TreeNode* right=lowestCommonAncestor(root->right, p, q);        if(left!=NULL&&right!=NULL)            return root;        else if(left==NULL&&right!=NULL)            return right;        else if(left!=NULL&&right==NULL)            return left;        else            return NULL;    }};
0 0
原创粉丝点击