Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:工程问题c语言求解 pdf 编辑:程序博客网 时间:2024/04/28 14:28
题目描述:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
给定先序遍历和中序遍历序列,还原树。
一次AC,代码如下:
public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder==null||preorder.length==0) return null; return buildRoot(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1); }public int findIndex(int[] inorder,int target){for(int i=0;i<inorder.length;i++){if(inorder[i]==target)return i;}return 0;}public TreeNode buildRoot(int[] preorder,int preleft,int preright,int[] inorder,int inleft,int inright){if(preleft==preright)return new TreeNode(preorder[preleft]);if(preleft>preright)return null;TreeNode root=new TreeNode(preorder[preleft]);int index=findIndex(inorder, preorder[preleft]);root.left=buildRoot(preorder, preleft+1, preleft+index-inleft, inorder, inleft, index-1);root.right=buildRoot(preorder, preleft+index-inleft+1, preright, inorder, index+1, inright);return root;}}
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
- Construct Binary Tree from Preorder and Inorder Traversal & Construct Binary Tree from Inorder and P
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- 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
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- 通过Ajax方式上传文件,使用FormData进行Ajax请求
- 关于img 底部留白的问题
- 使用apache benchmark(ab) 测试报错: apr_socket_recv: Connection timed out (110)
- ubuntu12.04下虚拟主机配置
- 【leetcode】Container with most water--python实现
- Construct Binary Tree from Preorder and Inorder Traversal
- as中设置自动联想不区分大小写
- PHP 数组排序二维或多维排序问题
- ARM Linux 3.x的设备树(Device Tree)
- syslog-ng配置说明
- 希尔排序
- apache+tomcat+Jfinal 2.2+dubbo2.5.4+zookeeper3.3.6 +redis+druid 分布式部署成功的一点心得(一)
- JavaScript Promise 告别异步乱嵌套
- C++11新特性