Very concise cpp solution use iterativety


  • -2
    H
    class Solution {
    public:
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            if(preorder.empty()||inorder.empty())return NULL;
            int rootVal=preorder.front();
            preorder.erase(preorder.begin());
            auto rootPos=find(inorder.begin(),inorder.end(),rootVal);
            TreeNode*root=new TreeNode(rootVal);
            vector<int> inorder_l(inorder.begin(),rootPos);
            vector<int> inorder_r(rootPos+1,inorder.end());
            root->left=buildTree(preorder,inorder_l);
            root->right=buildTree(preorder,inorder_r);
            return root;
        }
    };

  • 0
    W

    Please make the format more readable


  • 0
    A

    So is it a iterative solution or a recursive one? Check it, please.


  • 0
    S

    This is a very decent solution . Why are people downvoting it?


  • 0

    Probably because of its ugly "formatting" and because it doesn't use "iterativety", and possibly because its O(n^2) runtime is slow.


Log in to reply
 

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