[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:java数据类型取值范围 编辑:程序博客网 时间:2024/05/29 19:47
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) {return build(inorder, 0, inorder.length - 1, preorder, 0, preorder.length - 1);}public TreeNode build(int[] inorder, int lo1, int hi1, int[] preorder, int lo2, int hi2) {if (lo2 > hi2) return null;int index = getIndex(inorder, preorder[lo2]);TreeNode root = new TreeNode(preorder[lo2]);root.left = build(inorder, lo1, index - 1, preorder, lo2 + 1, lo2 + 1 + ((index - 1) - lo1));root.right = build(inorder, index + 1, hi1, preorder,lo2 + 1 + ((index - 1) - lo1) + 1, lo2 + 1 + ((index - 1) - lo1) + 1 + (hi1 - (index + 1)));return root;}public int getIndex(int[] array, int val) {for (int i = 0; i < array.length; i++) {if (array[i] == val) return i;}return -1;}}
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
- Umeng微信分享
- IOS APP 推荐
- ThreadLocal的使用
- Python的静态方法和类成员方法
- toad、oracle client、oracle DB版本问题,ora-12705错误
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- ztree中根据后台中传过来的node的id,将这个node的复选框置为不可用
- Android KeyCode列表
- HDU 1160 FatMouse's Speed (最長單調递增子序列 dp)
- 保存所有系统变量的方法
- 30 HTML CSS HTTP
- 9patch使用,图片自适应
- 服务器的压力测试
- Invalid Bundle Structure - The binary file '***.app/***.a' is not permitted