本文共 1107 字,大约阅读时间需要 3 分钟。
/** * 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; } int rootValue = postorder[postorder.length - 1]; int rootIndex = 0; for(int i = 0; i < inorder.length; i++) { if(inorder[i] == rootValue) { rootIndex = i; } } TreeNode root = new TreeNode(rootValue); root.left = buildTree(Arrays.copyOfRange(inorder, 0, rootIndex), Arrays.copyOfRange(postorder, 0, rootIndex)); root.right = buildTree(Arrays.copyOfRange(inorder, rootIndex + 1, inorder.length), Arrays.copyOfRange(postorder, rootIndex, postorder.length - 1)); return root; }}
转载地址:http://umhzi.baihongyu.com/