[leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int len=preorder.size();
        if(len==0)
            return {};
        else
            return build(preorder,inorder,0,len-1,0,len-1);
    }
    TreeNode* build(vector<int>& preorder, vector<int>& inorder,int preL,int preR,int inL,int inR)
    {
        if(preR<preL||inR<inL)
            return {};
            
        TreeNode* root=new TreeNode(preorder[preL]);
        if(preR==preL||inR==inL)
            return root;
            
        int mid;
        for(int i=inL;i<=inR;i++)
        {
            if(inorder[i]==preorder[preL])
            {
                mid=i;
                break;
            }
        }
        root->left=build(preorder,inorder,preL+1,preL+mid-inL,inL,mid-1);
        root->right=build(preorder,inorder,preL+1+mid-inL,preR,mid+1,inR);
        return root;
        
    }
};


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lady_lili/article/details/52356286
上一篇[leetcode]106. Construct Binary Tree from Inorder and Postorder Traversal
下一篇[leetcode]90. Subsets II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭