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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-05-30 16:12:22      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

Given inorder and postorder 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> &inorder, vector<int> &postorder) 
    {
        return build(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }
    TreeNode *build(vector<int> &inorder,int inl,int inr, vector<int> &postorder,int pl,int pr)
    {
        if(inl>inr) return NULL;
        
        TreeNode *root=new TreeNode(postorder[pr]);
        int index=inl;
        while(inorder[index]!=postorder[pr]) index++;
        root->left=build(inorder,inl,index-1,postorder,pl,pl+index-inl-1);
        root->right=build(inorder,index+1,inr,postorder,pr-(inr-index),pr-1);
    }
};
bubuko.com,布布扣

 

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

Construct Binary Tree from Inorder and Postorder Traversal

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759603.html

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