leetcode 105:从前序与中序遍历序列构造二叉树

使用二分法的方式  以上面的例子来说明,首先前序遍历中的第一个元素是root  也就是3

根据中序遍历   3之前的元素都属于左子树,3后面的元素都属于右子树  根据3在inorder中的位置可以知道左子树的个数和右子树的个数

我们可以得到左子树对应的前序遍历为[9] 对应的中序遍历为[9]  右子树的前序遍历为[15,20,7] 中序遍历为[15,20,7]

递归可得出结果

int find(int a,std::vector<int> b,int s,int t,int &c){
    c=0;
    for(int i=s;i<=t;i++){
        c++;
        if(a==b[i]){
            return i;
        }
    }
}

TreeNode *build(std::vector<int>& preorder, std::vector<int>& inorder,int s1,int t1,int s2,int t2){
    if(s1<=t1&&s2<=t2){
        TreeNode *root=new TreeNode(preorder[s1]);
        int c=0;
        int f=find(preorder[s1],inorder,s2,t2,c);
        root->left=build(preorder,inorder,s1+1,s1+c-1,s2,f-1);
        root->right=build(preorder,inorder,s1+c,t1,f+1,t2);
        return root;
    }else
        return NULL;

}

TreeNode* buildTree(std::vector<int>& preorder, std::vector<int>& inorder) {
    TreeNode *root=build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
    return root;
}

猜你喜欢

转载自blog.csdn.net/u013263891/article/details/86372320