C++详解Leetcode:105. Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:ubuntu系统声音主题包 编辑:程序博客网 时间:2024/06/08 02:40
原题
思路
通过二叉树的前序遍历和中序遍历来构建二叉树,通过递归可以很容易的解决这个问题,在遇到二叉树的问题,应该习惯先画图再来解决
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>& preorder, vector<int>& inorder) { int l1 = 0; int l2 = 0; int r1 = preorder.size() - 1; int r2 = inorder.size() - 1; TreeNode *s = (TreeNode*)malloc(sizeof(TreeNode)); //s = NULL; s = CreateBT(preorder, inorder, l1, r1, l2, r2); return s; } TreeNode* CreateBT(vector<int>& preorder, vector<int>& inorder, 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 = l2; i <= r2; i++) { if (inorder[i] == preorder[l1]) { break; } } s->val = inorder[i]; s->left = CreateBT(preorder, inorder, l1 + 1, l1 + i - l2, l2, i - 1); s->right = CreateBT(preorder, inorder, l1 + i - l2 + 1, r1, i + 1, r2); return s; }};
阅读全文
0 0
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode --- 105. Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]*105.Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode] 105.Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal LeetCode
- LeetCode#105. Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode *** 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode-105.Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode - 105. Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal
- 类数据与函数的关系
- 四大组件的匹配过程
- XML总结
- Maven学习笔记一
- C++ 静态成员
- C++详解Leetcode:105. Construct Binary Tree from Preorder and Inorder Traversal
- vtk面绘制的实现
- php 安装错误 undefined reference to `sapi_globals_id'
- bzoj2132: 圈地计划
- appium 代码实例
- python环境安装
- hpuoj 【1052】所爱图书【sort】
- Android Keycode详解
- Python Django项目基本配置