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
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder == null || inorder.length == 0) { return null; } TreeNode root = new TreeNode(postorder[postorder.length-1]); int mid = 0; for (int i = 0; i < inorder.length; i++) { if (inorder[i] == postorder[postorder.length-1]) { mid = i; break; } } root.left = buildTree(Arrays.copyOfRange(inorder, 0, mid), Arrays.copyOfRange(postorder, 0, mid)); root.right = buildTree(Arrays.copyOfRange(inorder, mid+1, inorder.length), Arrays.copyOfRange(postorder, mid, postorder.length-1)); return root; } }
LeetCode - Construct Binary Tree from Inorder and Postorder Traversal
原文:https://www.cnblogs.com/incrediblechangshuo/p/13814169.html