106. Construct Binary Tree from Inorder and Postorder Traversal
题目:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
链接: http://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
题解:
和上一题一样,不过这次的root是从post order的后面来找。
Time Complexity - O(n), Space Complexity - O(n)。
/** * Definition for a binary tree node. * 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 == null || postorder == null || inorder.length != postorder.length || inorder.length == 0) return null; return buildTree(postorder, 0, postorder.length - 1, inorder, 0, inorder.length - 1); } private TreeNode buildTree(int[] postorder, int postLo, int postHi, int[] inorder, int inLo, int inHi) { if(postLo > postHi || inLo > inHi) return null; TreeNode root = new TreeNode(postorder[postHi]); int rootIndex = 0; for(int i = inLo; i <= inHi; i++) { if(inorder[i] == root.val) { rootIndex = i; break; } } int leftTreeLen = rootIndex - inLo; root.left = buildTree(postorder, postLo, postLo + leftTreeLen - 1, inorder, inLo, rootIndex - 1); root.right = buildTree(postorder, postLo + leftTreeLen, postHi - 1, inorder, rootIndex + 1, inHi); return root; } }
二刷:
还是使用了一刷的办法,要注意递归的时候postorder的左子树范围是 [postLo, postLo + leftTreeLen - 1], 右子树是[postLo+ leftTreeLen, postHi - 1]。
可以使用HashMap保存inorder的key, value,这样在递归调用辅助方法时可以O(1)拿到rootVal,就不用顺序搜索了。
Java:
/** * Definition for a binary tree node. * 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 == null || postorder == null || inorder.length != postorder.length || inorder.length == 0) return null; return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); } private TreeNode buildTree(int[] inorder, int inLo, int inHi, int[] postorder, int postLo, int postHi) { if (inLo > inHi || postLo > postHi) return null; int rootVal = postorder[postHi]; int rootIndexAtInorder = inLo; while (rootIndexAtInorder <= inHi) { if (inorder[rootIndexAtInorder] == rootVal) break; rootIndexAtInorder++; } int leftTreeLen = rootIndexAtInorder - inLo; TreeNode root = new TreeNode(rootVal); root.left = buildTree(inorder, inLo, rootIndexAtInorder - 1, postorder, postLo, postLo + leftTreeLen - 1); root.right = buildTree(inorder, rootIndexAtInorder + 1, inHi, postorder, postLo + leftTreeLen, postHi - 1); return root; } }
Reference:
https://leetcode.com/discuss/10961/my-recursive-java-code-with-o-n-time-and-o-n-space