重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tqId=11157&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题解:

计算每次建树后pre和vin对应左右区间起始位置即可。

class Solution {
public:
    TreeNode* rebuild(vector &pre,vector &vin, int pleft, int pright, int vleft, int vright) {
        if (pleft > pright || vleft > vright) {
            return NULL;
        }
        TreeNode *root = new TreeNode(pre[pleft]);
        int k = 0;
        for (int i = vleft; i <= vright; i++) {
            if (vin[i] == pre[pleft]) {
                k = i;
                break;
            }
        }
        int llen = k - vleft, rlen = vright - k;
        root->left = rebuild(pre, vin, pleft + 1, pleft + llen, vleft, k - 1);
        root->right = rebuild(pre, vin, pleft + llen + 1, pleft + llen + rlen + 1, k + 1, vright);
        return root;
    }
    TreeNode* reConstructBinaryTree(vector pre,vector vin) {
        int n = pre.size();
        return rebuild(pre, vin, 0, n - 1, 0, n - 1);
    }
};

 

你可能感兴趣的:(剑指offer)