首页 > 其他 > 详细

Construct Binary Tree from Preorder and Inorder Traversal

时间:2014-05-30 16:03:21      阅读:378      评论:0      收藏:0      [点我收藏+]

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

Note:
You may assume that duplicates do not exist in the tree.

bubuko.com,布布扣
/**
 * Definition for binary tree
 * 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 buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
    }
    TreeNode *buildTree(const vector<int> &preorder,int pl,int pr,const vector<int> &inorder,int il,int ir)
    {
        if(pl>pr) return NULL;
        TreeNode* root=new TreeNode(preorder[pl]);
        int mid=il;
        while(inorder[mid]!=root->val) mid++;
        root->left=buildTree(preorder,pl+1,pl+mid-il,inorder,il,mid-1);
        root->right=buildTree(preorder,pr+1-(ir-mid),pr,inorder,mid+1,ir);
    }
};
bubuko.com,布布扣

 

Construct Binary Tree from Preorder and Inorder Traversal,布布扣,bubuko.com

Construct Binary Tree from Preorder and Inorder Traversal

原文:http://www.cnblogs.com/erictanghu/p/3759609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!