106. Construct Binary Tree from Inorder and Postorder Traversal - Medium
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
time: O(nlogn) ~ O(n^2), space: O(height)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder == null || postorder == null || inorder.length == 0 || inorder.length != postorder.length) { return null; } return buildTree(postorder, postorder.length - 1, inorder, 0, inorder.length - 1); } public TreeNode buildTree(int[] postorder, int post_start, int[] inorder, int in_start, int in_end) { if(post_start < 0 || in_start > in_end) { return null; } TreeNode root = new TreeNode(postorder[post_start]); int idx = 0; for(int i = in_start; i <= in_end; i++) { if(inorder[i] == postorder[post_start]) { idx = i; break; } } root.left = buildTree(postorder, post_start - (in_end - idx + 1), inorder, in_start, idx - 1); root.right = buildTree(postorder, post_start - 1, inorder, idx + 1, in_end); return root; } }