Recursive c++ solution, easy to understand


  • 0
    P
    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;
        }
    public:
        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.