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

[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-08-04 23:57:18      阅读:476      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   strong   io   for   ar   

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

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

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        int len = inorder.size();
        return build(inorder,0,len-1,postorder,0,len-1);
    }
private:
    TreeNode * build(vector<int> &inorder,int begInorder,int endInorder, vector<int> &postorder,int begpostorder,int endpostorder){
        
        if(begInorder>endInorder || begpostorder>endpostorder)
            return NULL;
        
        int val = postorder[endpostorder];
        TreeNode *root = new TreeNode(val);
        if(endInorder==begInorder)
            return root;
        int i,j=0;
        for(i=begInorder;i<=endInorder;i++,j++){
           if(inorder[i]==val)
               break;
        }
            
        root->left = build(inorder,begInorder,i-1,postorder,begpostorder,begpostorder+j-1);
        root->right = build(inorder,i+1,endInorder,postorder,begpostorder+j,endpostorder-1);
        return root;
    
    }
};

 

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

[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

标签:style   blog   color   os   strong   io   for   ar   

原文地址:http://www.cnblogs.com/Xylophone/p/3890980.html

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