劍指Offer——重建二叉樹——C

NO IMAGE

重建二叉樹

題目描述

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

思路:根據前序第一個字元是根的特性,再在中序中找到這個位置,分開,左邊的是左子樹,右邊的是右子樹。然後遞迴求出結果。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class
Solution {
public:
    struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int>
in) {
        int
len = in.size();
        if(len ==
0){
            return
NULL;
        }
        vector<int> left_pre, right_pre;
        vector<int> left_in, right_in;
        TreeNode *head =
new TreeNode(pre[0]);
        int
index = 0;
        for(int
i=0; i<len; i ){
            if(in[i] == pre[0]){
                index = i;
                break;
            }
        }
         
        for(int
i=0; i<index; i ){
            left_pre.push_back(pre[i 1]);
            left_in.push_back(in[i]);
        }
        for(int
i=index 1; i<len; i ){
            right_pre.push_back(pre[i]);
            right_in.push_back(in[i]);
        }
         
        //TreeNode* root = new TreeNode(pre[0]);
        head->left = reConstructBinaryTree(left_pre, left_in);
        head->right = reConstructBinaryTree(right_pre, right_in);       
         
        return
head;
    }
};