题目:

给定两个整数数组inorderpostorder ,其中inorder是二叉树的中序遍历,postorder是同一棵树的后序遍历,请构造并返回这颗二叉树
示例:
输入:inorder = [9, 3, 15, 20, 7], postorder = [9, 15, 7, 20, 3]
输出:[3, 9, 20, null, null, 15, 7]
示例:
输入:inorder = [-1], postorder = [-1]
输出:[-1]
代码:

  1. public TreeNode<Integer> buildTree(int[] inorder, int[] postorder) {
  2. if (inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0) {
  3. return null;
  4. }
  5. TreeNode<Integer> node = new TreeNode<>(postorder[postorder.length - 1]);
  6. int index = -1;
  7. int index2 = -1;
  8. for (int x = 0; x < inorder.length; x++) {
  9. //后序特点是 根在最后,中序特点是根左边是左子树,根右边是右子树
  10. //获取后序数组中最后一位值,在中序数组中找出值的位置,并记录index
  11. //获取在中序中index+1在的值,找出这个值在后序中的位置并记录 index2
  12. //最后切割两个数组.
  13. if (postorder[postorder.length - 1] == inorder[x]) {
  14. index = x;
  15. int[] leftI = null;
  16. int[] rightI = null;
  17. int[] leftP = null;
  18. int[] rightP = null;
  19. for (int y = 0; y < postorder.length; y++) {
  20. int temp = -1;
  21. if (index + 1 < inorder.length) {
  22. temp = index + 1;
  23. } else if (index + 1 == inorder.length) {
  24. temp = index;
  25. }
  26. if (inorder[temp] == postorder[y]) {
  27. index2 = y;
  28. leftI = Arrays.copyOfRange(inorder, 0, index);
  29. rightI = Arrays.copyOfRange(inorder, index + 1, inorder.length);
  30. leftP = Arrays.copyOfRange(postorder, 0, index2);
  31. rightP = Arrays.copyOfRange(postorder, index2, postorder.length - 1);
  32. break;
  33. }
  34. }
  35. node.lTreeNode = buildTree(leftI, leftP);
  36. node.rTreeNode = buildTree(rightI, rightP);
  37. }
  38. }
  39. return node;
  40. }