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

LeetCode:Construct Binary Tree from Preorder and Inorder Traversal

时间:2014-11-27 17:49:13      阅读:220      评论: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 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 
10 {
11     return buildTreeRecur(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
12 }
13 
14 TreeNode *buildTreeRecur(Iter pstart, Iter pend, Iter istart, Iter iend)
15 {
16     if(pstart == pend || istart == iend)
17         return NULL;
18     int ival = *pstart;
19     Iter ipos = find(istart, iend, ival);
20     TreeNode *res = new TreeNode(ival);
21     res->left = buildTreeRecur(pstart + 1, pstart+1+(ipos-istart), istart, ipos);
22     res->right = buildTreeRecur(pstart+1+(ipos-istart), pend, ipos+1, iend);
23     return res;
24 }

 

LeetCode:Construct Binary Tree from Preorder and Inorder Traversal

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

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

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