106. Construct Binary Tree from Inorder and Postorder Traversal
2024-10-11 12:09:28
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
========
利用:中序+后序遍历
====
code:
/**
* 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:
///
template<typename Iterator>
TreeNode *help_buildTree_ip(Iterator in_first,Iterator in_last,
Iterator post_first,Iterator post_last){
if(in_first == in_last) return nullptr;
if(post_first == post_last) return nullptr; auto val = *prev(post_last);
TreeNode *root = new TreeNode(val); auto in_root_pos = find(in_first,in_last,val);
auto left_size = distance(in_first,in_root_pos);
auto post_left_last = next(post_first,left_size); root->left = help_buildTree_ip(in_first,in_root_pos,post_first,post_left_last);
root->right = help_buildTree_ip(next(in_root_pos),in_last,post_left_last,prev(post_last)); return root;
}
TreeNode* buildTree_ip(vector<int> &inorder,vector<int> &postorder){
return help_buildTree_ip(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
}
};
最新文章
- 【记录】vmware fusion 7 windows 10 unidentified network
- 微信H5手指滑动屏蔽微信的默认效果
- C语言进行面向对象编程
- Apache日志配置详解(rotatelogs LogFormat)
- oracle的内置函数
- 《使用shell位置变量进行目录文件的备份小脚本》
- HDU-4737 A Bit Fun 维护
- PHP加解密相关函数
- c程序设计语言_习题1-18_删除输入流中每一行末尾的空格和制表符,并删除完全是空格的行
- android sax解析xml 文件 动态加载标题
- 简单说明CGI是什么
- Hadoop学习笔记二
- Android调试工具之ADB
- .Net Core微服务系列--开篇
- 0412ooday01.txt=============对象和类(上)
- 【实验四】[bx]和loop的使用
- 575. Distribute Candies
- PHP+Ajax实现文件上传功能
- JVM深度解析
- python购物车作业