Given inorder and postorder 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 { int[] ArrPostorder; int[] ArrInorder; Map<Integer, Integer> mapInorder = new HashMap<Integer, Integer>(); public TreeNode buildTree(int[] inorder, int[] postorder) { if (inorder.length == 0 || inorder == null) return null; ArrPostorder = postorder; ArrInorder = inorder; for (int i = 0; i < inorder.length; i++) mapInorder.put(inorder[i], i); int start = 0, end = postorder.length - 1; TreeNode root = new TreeNode(0); createTree(root, start, end, start, end); return root; } public void createTree(TreeNode root, int start1, int end1, int start2,int end2) { int subStart1,subStart2,subEnd1,subEnd2; int target = ArrPostorder[end2]; int indexInOrder = mapInorder.get(target); int len = end1-indexInOrder; int indexPostOrder = end2-len; if (start1 <= indexInOrder - 1) { subEnd1 = indexInOrder-1; subEnd2 = indexPostOrder - 1; root.left = new TreeNode(0); createTree(root.left, start1, subEnd1, start2, subEnd2); } root.val = target; if (indexInOrder + 1 <= end1) { subStart1 = indexInOrder + 1; subStart2 = indexPostOrder; subEnd2=end2-1; root.right = new TreeNode(0); createTree(root.right, subStart1, end1, subStart2, subEnd2); } return; } }
leetcode_106_Construct Binary Tree from Inorder and Postorder Traversal
原文地址:http://blog.csdn.net/mnmlist/article/details/44855457