码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Construct Binary Tree from Preorder and Inorder Traversal

时间:2015-05-13 18:47:08      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Title:

Given preorder and inorder traversal of a tree, construct the binary tree.

使用递归构建。

/**
 * 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:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return maker(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
    }
    template <typename Iter>
    TreeNode* maker(Iter pFirst,Iter pLast,Iter qFirst,Iter qLast){
        if (pFirst == pLast)
            return NULL;
        TreeNode *root = new TreeNode(*pFirst);
        Iter i = find(qFirst,qLast,*pFirst);
        int leftSize = distance(qFirst,i);
        root->left = maker(pFirst+1,pFirst+leftSize+1,qFirst,qFirst+leftSize);
        root->right = maker(pFirst+leftSize+1,pLast,qFirst+leftSize+1, qLast);
        return root;
    }
};

 

Title:

Given inorder and postorder traversal of a tree, construct the binary tree.

/**
 * 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:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return maker(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
    }
    
    template <typename Iter>
    TreeNode* maker(Iter pFirst,Iter pLast,Iter qFirst, Iter qLast){
        if (pFirst == pLast)
            return NULL;
        
        Iter iter = find(pFirst,pLast,*(qLast-1));
        int size = distance(pFirst,iter);
        TreeNode* root = new TreeNode(*(qLast-1));
        root->left = maker(pFirst,pFirst+size,qFirst,qFirst+size);
        root->right = maker(pFirst+size+1,pLast,qFirst+size,qLast-1);
        return root;
    }
};

 

LeetCode: Construct Binary Tree from Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4500844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!