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

(leetcode)Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-09-06 17:44:09      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

  

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

Note:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
13         return constructTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
14     }
15     TreeNode* constructTree(vector<int>& inorder,int begin1,int end1,vector<int>& postorder,int begin2,int end2)
16     {
17         if(begin1 > end1)
18             return NULL;
19         else if(begin1 == end1)
20             return new TreeNode(inorder[begin1]);
21         
22         TreeNode* root = new TreeNode(postorder[end2]);
23         int i = begin1;
24         for(; i <= end1; i ++)
25         {
26             if(inorder[i] == postorder[end2])
27                 break;
28         }
29         int leftlen = i-begin1;
30         
31         root->left = constructTree(inorder, begin1, begin1+leftlen-1, postorder, begin2, begin2+leftlen-1);
32         root->right = constructTree(inorder, begin1+leftlen+1, end1, postorder, begin2+leftlen, end2-1);
33         return root;
34     }
35 };

 

 


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

(leetcode)Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4786320.html

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