[leetcode]Construct Binary Tree from Inorder and Postorder Traversal
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.
算法:很基础。跟[leetcode]Construct Binary Tree from Preorder and Inorder Traversal类似,根据中序序列和后序序列构建二叉树。
1 public class Solution { 2 public TreeNode buildTree(int[] inorder, int[] postorder) { 3 if(inorder == null || postorder == null || inorder.length != postorder.length || inorder.length == 0) return null; 4 int length = inorder.length ; 5 int val = postorder[length - 1]; 6 int mid = 0; 7 for(int i = 0; i < length; i++){ 8 if(val == inorder[i]){ 9 mid = i; 10 break; 11 } 12 } 13 int[] leftInorder = Arrays.copyOfRange(inorder, 0, mid); 14 int[] leftPost = Arrays.copyOfRange(postorder, 0, mid); 15 int[] rightInorder = Arrays.copyOfRange(inorder, mid + 1, length); 16 int[] rightPost = Arrays.copyOfRange(postorder, mid, length - 1); 17 TreeNode root = new TreeNode(val); 18 root.left = buildTree(leftInorder,leftPost); 19 root.right = buildTree(rightInorder, rightPost); 20 return root; 21 22 } 23 }