重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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 {
    vector<int> pre, vin;
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        this->pre = pre;
        this->vin = vin;
        return dfs(0, pre.size() - 1, 0, vin.size() - 1);
    }

    TreeNode* dfs(int pl, int pr, int vl, int vr) {
        if (pl > pr) {
            return NULL;
        }
        TreeNode *root = new TreeNode(pre[pl]);

        int vm = vl;
        while (vin[vm] != pre[pl]) {
            ++vm;
        }
        int len = vm - vl;//计算左子树的个数
        root->left = dfs(pl + 1, pl + len, vl, vm - 1);//pl + 1到pl + len是左子树
        root->right = dfs(pl + len + 1, pr, vm + 1, vr);//pl + len + 1到pr是右子树

        return root;
    }
};
原文地址:https://www.cnblogs.com/jecyhw/p/6535827.html