C++详解Leetcode:106. Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:加入网络作协要求 编辑:程序博客网 时间:2024/05/22 08:06
原题
思路
通过二叉树的中序遍历和后序遍历来构建二叉树,通过递归可以很简单的解决
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: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { int l1 = 0; int l2 = 0; int r1 = inorder.size() - 1; int r2 = postorder.size() - 1; TreeNode *s = (TreeNode*)malloc(sizeof(TreeNode)); //s = NULL; s = CreateBT(inorder, postorder, l1, r1, l2, r2); return s; } TreeNode* CreateBT(vector<int>& inorder, vector<int>& postorder, int l1, int r1, int l2, int r2) { TreeNode* s; int i; if (l1 > r1) return NULL; s = (TreeNode*)malloc(sizeof(TreeNode)); s->left = s->right = NULL; for (i = l1; i <= r1; i++) { if (inorder[i] == postorder[r2]) { break; } } s->val = inorder[i]; s->left = CreateBT(inorder, postorder, l1, i - 1, l2, l2 + i -l1 - 1); s->right = CreateBT(inorder, postorder, i + 1, r1, l2 + i - l1, r2 - 1); return s; }};
阅读全文
0 0
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode --- 106. Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]*106.Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] 106.Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode#106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode *** 106. Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode-106.Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode - 106. Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode-106. Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】106. Construct Binary Tree from Inorder and Postorder Traversal
- 哲学家就餐问题
- linux下git环境变量配置
- 单词翻转
- java对象和Map互转及测试
- Codeforces contest 787 recordings
- C++详解Leetcode:106. Construct Binary Tree from Inorder and Postorder Traversal
- 精度丢失
- Codeforces contest 376&375 recordings
- 母函数 入门 + 模板
- 适配器模式
- [PAT乙级]1070. 结绳(25)
- 求和符号(Σ,sigma)
- 支配集、覆盖集、独立集、匹配与着色
- Python的逻辑控制true/false和循环