Recursive c++ solution, easy to understand

  • 0
    class Solution {
        TreeNode* BD(vector<int>::iterator pre,vector<int>::iterator in,int n){
            if(n<=0) return NULL;
            TreeNode *root = new TreeNode(*pre);
            int left = find(in,in+n,*pre)-in;
            root->left = BD(pre+1,in,left);
            root->right = BD(pre+1+left,in+1+left,n-1-left);
            return root;
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            return BD(preorder.begin(),inorder.begin(),preorder.size());

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.