美文网首页
2.Construct Binary Tree from Pre

2.Construct Binary Tree from Pre

作者: Anaven | 来源:发表于2017-01-02 11:07 被阅读0次

    https://leetcode.com/problems/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:
        typedef vector<int>::iterator Iter;
    
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            return buildTree(inorder.begin(), inorder.end(), preorder.begin(), preorder.end());
        }
    
        TreeNode *buildTree(Iter istart, Iter iend, Iter pstart, Iter pend) {
            if (istart == iend) {
                return nullptr;
            }
    
            TreeNode* node = new TreeNode(*pstart);
            
            Iter ipos = find(istart, iend, *pstart);
            node->left = buildTree(istart, ipos, pstart+1, pstart+(ipos-istart)+1);
            node->right = buildTree(ipos+1, iend, pstart+(ipos-istart)+1, pend);
    
            return node;
        }
    };
    

    相关文章

      网友评论

          本文标题:2.Construct Binary Tree from Pre

          本文链接:https://www.haomeiwen.com/subject/njdwvttx.html