Construct Binary Tree from Preorder and Inorder Traversal
2013-11-16 06:37
190 查看
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
本来想先对inorder array做预处理存上val对应的index,结果发现 val可能有duplicates。
Note:
You may assume that duplicates do not exist in the tree.
本来想先对inorder array做预处理存上val对应的index,结果发现 val可能有duplicates。
/**duplicates * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return preorder_inorder(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); } public TreeNode preorder_inorder(int[] pre, int ps, int pe, int[] in, int is, int ie){ if(ps > pe || is > ie) return null; TreeNode root = new TreeNode(pre[ps]); int ind = 0; for(int i = is; i <= ie; i++) if(in[i] == root.val){ ind = i; break; } int len = ind - is; root.left = preorder_inorder(pre, ps + 1, ps + len, in, is, ind - 1); root.right = preorder_inorder(pre, ps + 1 + len, pe, in, ind + 1, ie); return root; } }
相关文章推荐
- leetcode - Construct Binary Tree from Preorder and Inorder Traversal
- 5.2.1—二叉树的构建—Construct Binary Tree from Preorder and Inorder Traversal
- 105. 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
- Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal (Tree; DFS)
- leetcode-Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal (&&Preorder and Inorder Traversal )——数据结构和算法的基本问题
- leetcode第一刷_Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium
- [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
- 105 Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal