题目描述

  1. 给出一个二叉树的先序和中序遍历,还原这棵二叉树
  1. /**
  2. * Definition for binary tree
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. /**
  12. * 重建二叉树
  13. *
  14. * @param pre
  15. * @param in
  16. * @return
  17. */
  18. public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
  19. return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
  20. }
  21. /**
  22. * 5
  23. * / \
  24. * 3 2
  25. * / \ / \
  26. * 1 4 6 8
  27. * pre[根左右]:5 3 1 4 2 6 8
  28. * in[左根右] :1 3 4 5 6 2 8
  29. * out[左右根]:1 4 3 6 8 2 5
  30. * @param pre
  31. * @param preL
  32. * @param preR
  33. * @param in
  34. * @param inL
  35. * @param inR
  36. * @return
  37. */
  38. private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int[] in, int inL, int inR) {
  39. if (preL > preR || inL > inR) {
  40. return null;
  41. }
  42. TreeNode root = new TreeNode(pre[preL]);
  43. int i = inL;
  44. while (in[i] != pre[preL] && i <= inR) {
  45. ++i;
  46. }
  47. /**
  48. * * 5
  49. * * / \
  50. * * 3 2
  51. * * / \ / \
  52. * * 1 4 6 8
  53. * * pre[根左右]:5 3 1 4 2 6 8
  54. * * in [左根右]:1 3 4 5 6 2 8
  55. * * out[左右根]:1 4 3 6 8 2 5
  56. */
  57. root.left = reConstructBinaryTree(pre, preL + 1, preL + (i - inL), in, inL, i - 1);
  58. root.right = reConstructBinaryTree(pre, preL + (i - inL) + 1, preR, in, i + 1, inR);
  59. return root;
  60. }
  61. }