[Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal
2015-04-04 23:39
477 查看
Given inorder and postorder traversal of a tree, construct the binary 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[] inorder, int[] postorder) { if(inorder.length != postorder.length) return null; return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); } private TreeNode buildTree(int[] inorder, int instart, int inend, int[] postorder, int poststart, int postend){ if(instart > inend) return null; int position = findPosition(inorder, instart, inend, postorder[postend]); TreeNode root = new TreeNode(postorder[postend]); root.left = buildTree(inorder, instart, position - 1, postorder, poststart, postend - inend + position - 1); root.right = buildTree(inorder, position + 1, inend, postorder, postend -inend + position , postend - 1); return root; } private int findPosition(int[] arr, int start, int end, int key) { int i; for (i = start; i <= end; i++) { if (arr[i] == key) return i; } return -1; } }
相关文章推荐
- LeetCode 105/106 Construct Binary Tree from Preorder/Postorder and Inorder Traversal
- leetcode || 106、Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal - LeetCode 106
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode 106] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode --- 106. Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] 106.Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode_106 Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode#106 Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode 106] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: 106_Construct Binary Tree from Inorder and Postorder Traversal | 根据中序和后序遍历构建二叉树 | Medium
- [Leetcode 79] 106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode---(106)Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
- leetcode_106_Construct Binary Tree from Inorder and Postorder Traversal
- leetcode[106]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal [106]
- [LeetCode]106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal