LeetCode | Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

题目解析:

前序遍历的第一个结点一定为根结点,然后找到中序遍历的根结点所在的位置,分成两部分,递归遍历即可。充分利用遍历的特性进行求解。题目中没有要求存在重复数据,如果有重复数据,要判断分割的两部分长度是否相等。

class Solution{
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        if(preorder.size() != inorder.size())
            return NULL;

        return generateSub(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    }
    TreeNode *generateSub(vector<int> &preorder,int begin1,int end1,vector<int> &inorder,int begin2,int end2){
        if(begin1>end1 || begin2>end2)
            return NULL;
        int i;
        for(i = begin2;i<=end2;i++){
            if(preorder[begin1] == inorder[i])
                break;
        }
        TreeNode *p = new TreeNode(preorder[begin1]);
        p->left = generateSub(preorder,begin1+1,begin1+i-begin2,inorder,begin2,i-1);
        p->right = generateSub(preorder,begin1+i-begin2+1,end1,inorder,i+1,end2);
        return p;
    }
};
点赞