Leetcode[105]-Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:html5 java 编辑:程序博客网 时间:2024/05/18 17:56
题目描述:给定前序和中序序列,构建一颗二叉树
节点定义为:
struct TreeNode{int val;TreeNode * left;TreeNode * right;TreeNode (int x) : val(x),left(NULL),right(NULL){}};
很明显,可以将大问题划分成子问题,用递归实现
时间复杂度为O(N),空间复杂度为O(logN)
class Solution{public : TreeNode * construct(vector<int> & preorder,vector<int> & inorder){int len = preorder.size();if(len <= 0) return NULL;TreeNode * ans = createTree(preorder,0,len-1,inorder,0,len-1);return ans;}TreeNode * createTree(vector<int> & preorder,int prestart,int preend,vector<int> & inorder,int instart,int inend){if(instart > inend) return NULL;int index;for(int i = instart;i<=inend;i++){if(preorder[prestart] == inorder[i]){index = i;break;}}int lenth = index-instart;TreeNode * root = new TreeNode(preorder[prestart]);root->left = createTree(preorder,prestart+1,prestart+lenth,inorder,instart,index-1);root->right = createTree(preorder,prestart+lenth+1,preend,inorder,index+1,inend);return root;}};
0 0
- LeetCode(105)Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal [105]
- 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
- Construct Binary Tree from Preorder and Inorder Traversal LeetCode 105
- 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
- iOS UIView 切其中某一个圆角
- Java web分层设计
- C语言中的常用变量
- MySQL常用操作
- 入门程序员在开发过程中遇到的困难
- Leetcode[105]-Construct Binary Tree from Preorder and Inorder Traversal
- 人工蜂群算法
- 关于fclose报错问题
- 安装过cygwin后删不掉的问题
- JSP/Servlet 工作原理
- golang语法学习(二):控制语句,函数,以及错误处理。
- 3.加载其它扇区
- 激光雷达学习笔记(三)特征提取
- Hadoop家族产品