LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:python redis模块 编辑:程序博客网 时间:2024/04/29 22:54
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void build(vector<int> &preorder, vector<int> &inorder, TreeNode* &root, int r, int nStart, int nEnd) { if (nStart >= nEnd) return; int num = preorder[r]; root = new TreeNode(num); int idx = nStart; while(idx < nEnd && inorder[idx] != num) ++idx; if (idx < nEnd) build(preorder, inorder, root->left, r+1, nStart, idx); if (nEnd > idx + 1) build(preorder, inorder, root->right, r+idx-nStart+1, idx+1, nEnd); } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { // Start typing your C/C++ solution below // DO NOT write int main() function int nSize = preorder.size(); if (nSize == 0) return NULL; TreeNode* root = NULL; build(preorder, inorder, root, 0, 0, nSize); return root; }};
- *(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
- jquery动态增加表格表单行来插入数据-------遇到的兼容问题和radio问题
- 表现层 freemaker学习2
- PHP中的替代语法(冒号、endif、endwhile、endfor)
- java语言规范
- 表现层 freemaker学习3
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- [小e笔记]之10gR2+redhat5.3+32bit+RAC安装
- SQL Server T-SQL高级查询
- html效果总结记录
- Why BIOS loads MBR into 0x7C00 in x86 ?
- Java编程中“为了性能”尽量要做到的一些地方
- MyEclipse 8.5 安装配置和插件安装指南
- 表现层 freemaker学习3
- 【数据库】网易校园招聘笔试题--数据库事务的定义,属性,以及隔离级别