標籤:
Given inorder and postorder traversal of a tree, construct the binary tree.
Notice
You may assume that duplicates do not exist in the tree.
Example
Given inorder [1,2,3] and postorder [1,3,2], return a tree:
2 / 1 3
分析:這是非常典型的遞迴問題,postorder的最後一個是root,在inorder裡面找出root的位置,左邊部分為左子樹,右邊部分為右子樹,稍微麻煩的部分就是確定左子樹和右子樹的starting index。
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 tree17 *@param postorder : A list of integers that postorder traversal of a tree18 *@return : Root of a tree19 */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