Leetcode 105
来源:互联网 发布:java从入门到精通目录 编辑:程序博客网 时间:2024/05/01 02:10
题意
根据二叉树的前序遍历结果和中序遍历结果重构二叉树。
思路
根据前序遍历和中序遍历的性质我们可以知道前序遍历的第一个节点一定是二叉树的根节点,中序遍历根节点之前的是其左子树,根节点之后的是其右子树。
于是我们在中序遍历的数组中找到当前位置pos,那么在中序遍历中,从0到pos - 1一定是二叉树的左子树,从pos + 1到n一定是二叉树的右子树,递归的去做就好。
代码
/** * 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* build(vector<int>& a, int l1, int r1, vector<int>& b, int l2, int r2) { if (l1 == r1) { TreeNode* node = new TreeNode(a[l1]); return node; } else if (l1 > r1) { return NULL; } TreeNode* root = new TreeNode(a[l1]); int off = 0; for (int i = l2; i <= r2; i++) { if (b[i] == a[l1]) {off = i - l2; break;} } root->left = build(a, l1 + 1, l1 + off, b, l2, l2 + off - 1); root->right = build(a, l1 + off + 1, r1, b, l2 + off + 1, r2); return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); }};
0 0
- Leetcode 105
- LeetCode #105
- LeetCode 105
- LeetCode 105 Rotate Image
- [LeetCode] 105 & 106
- leetcode #105 in cpp
- Leetcode no. 105
- leetCode练习(105)
- leetcode 105&106
- leetcode 105 & 106
- [Leetcode] 105, 106, 96
- Leetcode 105&106
- [LeetCode] 105: Spiral Matrix
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- 国外大神说-在编程中使用If语句的潜在危险
- Struts2的执行流程
- linux平台Android studio安装步骤
- Andorid_API19设置状态栏颜色
- 算法
- Leetcode 105
- Crontab 小细节
- Java程序实现根据经纬度计算GPS点的距离
- Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)
- android studio 往git上推送项目
- 远程连接MySQL报错ERROR 2003解决办法
- 通过汇编代码来理解计算机是如何工作的
- Ubuntu安装g++-4.8
- Qcharts之柱状图