leetcode:构建二叉树

Construct Binary Tree from Inorder and Postorder Traversal

 

class Solution {

public:
    TreeNode *buildTree(vector &inorder, vector &postorder) {
        int len = postorder.size();
        TreeNode *node = buildTree(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
        return node;
    }
private:
    TreeNode *buildTree(vector::iterator in_first,vector::iterator in_last,vector::iterator post_first,vector::iterator post_last)
    {
        if(in_first == in_last)
            return NULL;
        if(post_first == post_last)
            return NULL;


        TreeNode *node = new TreeNode(*(post_last-1));
        vector::iterator it = find(in_first,in_last,*(post_last-1));
        int leftSize = it - in_first;


        node->left = buildTree(in_first,it,post_first,post_first+leftSize);
        node->right = buildTree(it+1,in_last,post_first+leftSize,post_last-1);
        
        return node;
    }

};


Construct Binary Tree from Preorder and Inorder Traversal

 


class Solution {
public:
    TreeNode *buildTree(vector &preorder, vector &inorder) {
        TreeNode* node = buildTree(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
        return node;
    }
//    template
    TreeNode* buildTree(vector::iterator pre_first, vector::iterator pre_last,vector::iterator in_first, vector::iterator in_last)
    {
        if(pre_first == pre_last)
            return NULL;
        if(in_first == in_last)
            return NULL;


        TreeNode* node  = new TreeNode(*pre_first);
        vector::iterator root = find(in_first,in_last,*pre_first);
        int leftSize = root - in_first;//distance(in_first,root);


        node->left = buildTree(pre_first+1,pre_first+leftSize+1,in_first,root);
        node->right = buildTree(pre_first+leftSize+1,pre_last,root+1,in_last);


        return node;
    }
};

你可能感兴趣的:(leetcode:构建二叉树)