[Leetcode]Construct Binary Tree from Inorder and Postorder Traversal
2015-10-24 14:44
363 查看
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/*algorithm: divide and conquer
from postorder to get the root,
based on root, separate the inorder list to two list
recrusive this process,
*///[start,end) [1,2,3] [1,3,2]
TreeNode* buildTreeSub(vector<int>&in,vector<int>&post,int is,int ilen,int ps,int plen)
{
if(plen < 1)return NULL;
int v = post[ps + plen - 1];
TreeNode* root = new TreeNode(v);
int i = 0;
for(i = 0;i < ilen && in[i+is] != v;++i);
root->left = buildTreeSub(in,post,is,i,ps,i);
root->right = buildTreeSub(in,post,is+i+1,ilen-(i+1),ps+i,plen-(i+1));
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTreeSub(inorder,postorder,0,inorder.size(),0,postorder.size());
}
};
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/*algorithm: divide and conquer
from postorder to get the root,
based on root, separate the inorder list to two list
recrusive this process,
*///[start,end) [1,2,3] [1,3,2]
TreeNode* buildTreeSub(vector<int>&in,vector<int>&post,int is,int ilen,int ps,int plen)
{
if(plen < 1)return NULL;
int v = post[ps + plen - 1];
TreeNode* root = new TreeNode(v);
int i = 0;
for(i = 0;i < ilen && in[i+is] != v;++i);
root->left = buildTreeSub(in,post,is,i,ps,i);
root->right = buildTreeSub(in,post,is+i+1,ilen-(i+1),ps+i,plen-(i+1));
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTreeSub(inorder,postorder,0,inorder.size(),0,postorder.size());
}
};
相关文章推荐
- 360WiFi链接问题
- SequenceFile使用随笔
- GDI+之水印图片和缩略图
- PropertiesHelper——配置文件读取和写入工具类
- [learn ros] A fake battery simulator
- Servlet 工作原理解析
- DP-HDU-1257-最少拦截系统
- [ACM] HDU 3395 Special Fish (最大重量二分图匹配,KM算法)
- senchatouch tabPanel 在面板跳转时执行自定义函数 handler()
- poj 3723 Conscription
- easyui动态隐藏/显示tab页
- navicat无法访问mysql的问题 包括(1130和1045)
- First Blog
- 1003. 我要通过!(20)
- 使用锁实现同步
- 《学习OpenCV》 第四章 习题六
- VC++6.0 VS2005 VS2008 VS2010 VS2012 VS2013 编译 连接时候到底调用了那些东东
- NSSet类型 以及与NSArray区别
- 自定义函数1
- Centos6.3添加解码器播放MP3和常见视频音频