[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:孤城网络 编辑:程序博客网 时间:2024/06/05 10:44
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
问题描述:给定一个二叉树的前序遍历和中序遍历序列,构建这个二叉树。
二叉树的问题通常可以采用递归的方式。
知道一个子树的前序,那么就可以知道该子树的根,然后在中序中找到这个根,就可以知道左右子树的前序和中序遍历序列。
class Solution {public: typedef vector<int>::iterator bt_iter; TreeNode *build(bt_iter pre_beg, bt_iter pre_end, bt_iter in_beg, bt_iter in_end) { if(pre_beg == pre_end) return NULL; int root_val = *pre_beg; bt_iter rt_it = find(in_beg, in_end, root_val); bt_iter left_end = pre_beg + (rt_it - in_beg); TreeNode *child_root = new TreeNode(root_val); child_root->left = build(pre_beg + 1, left_end + 1, in_beg, rt_it - 1); child_root->right = build(left_end + 1, pre_end, rt_it + 1, in_end); return child_root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return build(preorder.begin(), preorder.end(), inorder.begin(), inorder.end()); }};
- *(leetcode) Construct Binary Tree from Preorder and Inorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode][tree] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 109: Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode-Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode - Construct Binary Tree from Preorder and Inorder Traversal
- [leetCode] Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- oracle各版本的区别
- 详解linux系统的启动过程及系统初始化
- Linux查找指令
- 动态设定分栏数
- proxy silbing 原理分析
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- Ubuntu12.04实现root用户登录
- 自己在ubuntu里常用的便捷操作
- java中map的操作
- Java bit / byte 基本数据类型
- Misra-c 整理笔记
- string的用法
- F5 Networks:助力中国4G市场
- jquery简单的多级下拉菜单