标签:
Given inorder and postorder traversal of a tree, construct the binary tree.
You may assume that duplicates do not exist in the tree.
Given inorder [1,2,3]
and postorder [1,3,2]
, return a tree:
2
/ 1 3
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 13 14 public class Solution { 15 /** 16 *@param inorder : A list of integers that inorder traversal of a tree 17 *@param postorder : A list of integers that postorder traversal of a tree 18 *@return : Root of a tree 19 */ 20 public TreeNode buildTree(int[] inorder, int[] postorder) { 21 if (inorder == null || postorder == null || postorder.length == 0 || inorder.length != postorder.length) return null; 22 23 return buildTree(inorder, 0, postorder, 0, inorder.length); 24 25 } 26 27 public TreeNode buildTree(int[] inorder, int inStart, int[] postorder, int postStart, int length) { 28 if (length <= 0) return null; 29 TreeNode root = new TreeNode(postorder[postStart + length - 1]); 30 31 int index = findIndex(inorder, root.val); 32 root.left = buildTree(inorder, inStart, postorder, postStart, index - inStart); 33 root.right = buildTree(inorder, index + 1, postorder, postStart + (index - inStart), length - (index - inStart) - 1); 34 35 return root; 36 37 } 38 39 public int findIndex(int[] inorder, int val) { 40 for (int i = 0; i < inorder.length; i++) { 41 if (inorder[i] == val) { 42 return i; 43 } 44 } 45 return -1; 46 } 47 }
Construct Binary Tree from Inorder and Postorder Traversal
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5652021.html