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

LeetCode:Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-11-27 17:45:31      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   color   os   sp   on   div   art   

要求:根据中序和后序遍历序列构建一棵二叉树

代码如下:

 1 struct TreeNode {
 2     int            val;
 3     TreeNode    *left;
 4     TreeNode    *right;
 5     TreeNode(int x): val(x),left(NULL), right(NULL) {}
 6 };
 7 
 8 typedef vector<int>::iterator Iter;
 9 
10 TreeNode *buildTreeFromInorderPostorder(vector<int> &inorder, vector<int> &postorder)
11 {
12     return buildBinaryTreeResur(inorder.begin(), inorder.end(), postorder.begin(), postorder.end());
13 }
14 
15 TreeNode *buildBinaryTreeResur(Iter istart, Iter iend, Iter pstart, Iter pend)
16 {
17     if (istart == iend || pstart == pend)
18         return NULL;
19     int ival = *(pend-1);
20     Iter ptemp = find(istart, iend, ival);
21     TreeNode *res = new TreeNode(ival);
22     res->left = buildBinaryTreeResur(istart, ptemp, pstart, pstart+(ptemp-istart));
23     res->right = buildBinaryTreeResur(ptemp+1, iend, pstart+(ptemp-istart), pend-1);
24     return res;
25 }

 

LeetCode:Construct Binary Tree from Inorder and Postorder Traversal

标签:style   blog   ar   color   os   sp   on   div   art   

原文地址:http://www.cnblogs.com/bakari/p/4126702.html

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