1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| public class SortClass {
public static void main(String[] args){ int[] preorder = {1,2,4,7,3,5,6,8}; int[] inorder = {4,7,2,1,5,3,8,6}; try { BinaryTreeNode binaryTreeNode= constructCore(preorder,inorder); System.out.println(binaryTreeNode); } catch (Exception e) { e.printStackTrace(); } } private static class BinaryTreeNode {
public int value; public BinaryTreeNode leftNode; public BinaryTreeNode rightNode;
@Override public String toString() { return "BinaryTreeNode{" + "value=" + value + ", leftNode=" + leftNode + ", rightNode=" + rightNode + '}'; } } private static BinaryTreeNode constructCore(int[] preorder, int[] inorder) throws Exception { if (preorder == null || inorder == null) { return null; } if (preorder.length != inorder.length) { throw new Exception("长度不一样,非法的输入"); } BinaryTreeNode root = new BinaryTreeNode(); for (int i = 0; i < inorder.length; i++) { if (inorder[i] == preorder[0]) { root.value = inorder[i]; System.out.println(root.value); root.leftNode = constructCore(Arrays.copyOfRange(preorder, 1, i + 1), Arrays.copyOfRange(inorder, 0, i)); root.rightNode = constructCore(Arrays.copyOfRange(preorder, i + 1, preorder.length), Arrays.copyOfRange(inorder, i + 1, inorder.length)); } } return root; } }
|