算法:Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:软件测试职位描述 编辑:程序博客网 时间:2024/06/05 06:10
Given preorder and inorder traversal of a tree, construct the binary 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 {private: // 为了避免数组的复杂操作,这里直接用左右界和数组的引用来代表一段前序遍历和中序遍历 // 即preorder[lp, rp]代表了当前子树的前序遍历,inorder[li, ri]代表了当前子树的中序遍历 TreeNode* work(vector<int>& preorder, vector<int>& inorder, int lp, int rp, int li, int ri) { // 判断长度为0的情况 if (lp > rp) return NULL; // 设置根节点 TreeNode *root = new TreeNode(preorder[lp]); // 找到根节点在inorder中的位置 for (int k = li; k <= ri; k++) { if (preorder[lp] == inorder[k]) { // 分治处理两棵子树 root -> left = work(preorder, inorder, lp + 1, lp + (k - li), li, k - 1); root -> right = work(preorder, inorder, lp + (k - li) + 1, rp, k + 1, ri); } } // 返回这棵子树 return root; } public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { if(preorder.size()==0 || inorder.size()==0) return NULL; return work(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1); }};
0 0
- 算法:Construct Binary Tree from Preorder and Inorder Traversal
- *(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
- Construct Binary Tree from Preorder and Inorder Traversal & Construct Binary Tree from Inorder and P
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- 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
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- 将excel转成pdf有哪些方法
- js调用新浪天气预报的方法
- Linux文件系统以及目录结构简介
- QSqlQuery直接使用sql语句与采用bindValue的比较
- 编译Caffe-Win错误集锦
- 算法:Construct Binary Tree from Preorder and Inorder Traversal
- OpenCV3.1中读写图像与读写像素
- unity打包ios过大,ios压缩技巧
- 如何获取百度地图API的密钥以及调用百度地图api
- php-fpm 启动脚本
- 数据结构实验之链表五:单链表的拆分
- 用redis轻松实现秒杀系统
- Linux中断子系统 - softirq
- Gradle 完整指南(Android)