LeetCode | Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:网络购物中心 编辑:程序博客网 时间:2024/05/15 05:49
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:本题给出二叉树的先序遍历和中序遍历,然后构建出这颗二叉树。
分析:先序遍历的顺序是根结点、左子树、右子树。中序遍历的顺序是左子树,根结点,右子树。因此,假设假设先序遍历的结果存储在A向量中,中序遍历的结果存储在B向量中,那么A向量的第一个元素A0是二叉树的根结点,B向量中在A0元素前面的就是左子树的结点(若不存在,左子树就为空),A0元素后面的结点就是右子树的结点(若不存在,右子树就为空)。然后对上述所得的左子树Ltree和右子树Rtree继续采用上述方法。取A向量的第二个元素A1,它是二叉树根结点的左子树的根,B向量中在A1前面的元素就是以A1为根的二叉树的左子树的所有结点,B向量中A1后面的元素就是以A1为根的二叉树的右子树的所有结点。在程序该方法可以采用递归实现。
class Solution {public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {if(inorder.size() > 0){this->preorder = preorder;this->inorder = inorder;cur = 0;return buildSubTree(0,inorder.size()-1);}elsereturn NULL; }TreeNode* buildSubTree(int from, int to)//从第from个结点到第to个结点,构造二叉树{TreeNode* root = new TreeNode(preorder[cur]);//构造根结点int index = findinorder(root->val);//在中序遍历中找到根结点的位置cur++;if(index > from)root->left = buildSubTree(from,index-1);//构造左子树if(index < to)root->right = buildSubTree(index+1,to);//构造右子树return root;}int findinorder(int p){for(int i=0; i<inorder.size(); ++i)if(p==inorder[i])return i;}private:vector<int> preorder;vector<int> inorder;int cur;};
0 0
- *(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
- 匿名管道-实例
- Ext.Net 后台主页布局
- 25岁的我们,该懂事了
- C/C++ 删除指定目录
- 代码中设置背景颜色
- LeetCode | Construct Binary Tree from Preorder and Inorder Traversal
- 用Buddy算法来改进uCos-ii内存管理方案
- 解决navicat连接数据库时报ORA-28547问题
- 黑马程序员--java复习之IO包中其他类
- java文件读写操作大全
- 判断字符串中中只包含数字字母
- 破解TexturePacker加密资源:使用IDA
- Android获取当前手机号码
- CSU1567:Reverse Rot(DFS)