LeetCode---(106)Construct Binary Tree from Inorder and Postorder Traversal
2015-07-15 18:48
369 查看
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:
TreeNode* help(vector<int>& inorder, vector<int>& postorder,int fromi,int fromp,int length)
{
if(length==0)
return 0;
TreeNode* root=new TreeNode(postorder[fromp+length-1]);
int i;
for(i=fromi;inorder[i]!=postorder[fromp+length-1];i++)
;
root->left=help(inorder,postorder,fromi,fromp,i-fromi);
root->right=help(inorder,postorder,i+1,fromp+i-fromi,length-1-i+fromi);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return help(inorder,postorder,0,0,inorder.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:
TreeNode* help(vector<int>& inorder, vector<int>& postorder,int fromi,int fromp,int length)
{
if(length==0)
return 0;
TreeNode* root=new TreeNode(postorder[fromp+length-1]);
int i;
for(i=fromi;inorder[i]!=postorder[fromp+length-1];i++)
;
root->left=help(inorder,postorder,fromi,fromp,i-fromi);
root->right=help(inorder,postorder,i+1,fromp+i-fromi,length-1-i+fromi);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return help(inorder,postorder,0,0,inorder.size());
}
};
相关文章推荐
- ArrayAdapter中的android.R.id.text1是什么
- 关于中文乱码问题
- 辗转到了Android
- JUnit4.8.2来源分析-6.1 排序和过滤
- javaScript基础概念整理1(数据类型)
- Windows程序设计学习笔记(五)——菜单资源和加速键的使用
- [三]三种 hls 解析源码 vlc ffmpeg exoplayer
- Android Intents with Chrome
- 程序设计
- UIImagePickerController
- 开了个博客,然而并不知道该记写什么哎
- [二]三种 hls 解析源码 vlc ffmpeg exoplayer
- JAVA基础(2)——分支和循环结构
- jQuery--自定义插件
- 正则表达式,一些例子
- 9.Laravel5学习笔记:在laravel中注册自己的服务到容器中
- WebService大讲堂之Axis2(1):用POJO实现0配置的WebService
- java获取时间,本周,本月,本季度的起始。
- Codeforces Round #312 (Div. 2) 完整题解
- Android 录音