[劍指offer][[Leetcode]面試題7:重建二叉樹

1.題目

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

2.code

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        int prelen=pre.size();
        int vinlen=vin.size();
        if(prelen==0||vinlen==0)
            return NULL;
        else
            return Construct(pre,0,prelen-1,vin,0,vinlen-1);
    }
    TreeNode* Construct(vector<int>pre,int prestart,int preend,vector<int>vin,int vinstart,int vinend)
    {
        //判斷只有一個節點的情況
        TreeNode* root=new TreeNode(NULL);
        root->val=pre[prestart];
        if(prestart==preend)
        {
            if(vinstart==vinend&&pre[prestart]==vin[vinstart])
                return root;
        }
        //在中序序列中找對應的值
        int rootval=pre[prestart];
        int rootpos=vinstart;
        while(vin[rootpos]!=rootval&&rootpos<=vinend)
            rootpos++;
        //while(rootpos>vinend) 如何表示錯誤信息
        //找到根節點
        int leftsize=rootpos-vinstart;
        //左子樹存在
        if(leftsize>0)
            root->left=Construct(pre,prestart+1,prestart+leftsize,vin,vinstart,rootpos-1);
        //右子樹存在:前序序列長度大於左子樹大小,那麼就說明有右子樹
        if(leftsize<(preend-prestart))
            root->right=Construct(pre,prestart+leftsize+1,preend,vin,rootpos+1,vinend);
        return root;
    }
};

3.分析

注意邊界情況:遞歸終止的條件;記得明確,當pre和vin都只剩下一個元素的時候。 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章