Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. 1
  2. /
  3. 2 2
  4. /
  5. 5 3
  6.  
  7. 6
  8.  
  9. Sorted array: 1 2 2 3 5 6
  10. Original indexes: 1 0 4 5 2 3
  11.  
  12. First and second steps:
  13.  
  14. 1(1)
  15. /
  16. 2(0)
  17.  
  18. Third and fourth steps:
  19.  
  20. 1(1)
  21. /
  22. 2(0) 2(4)
  23.  
  24. 3(5)
  25.  
  26. Final two steps:
  27.  
  28.  
  29. 1(1)
  30. /
  31. 2(0) 2(4)
  32. /
  33. 5(2) 3(5)
  34.  
  35. 6(3)
  36.  
  37. 1st step
  38.  
  39. 2 <--
  40.  
  41. 2nd step
  42.  
  43. 1 <--
  44. /
  45. 2
  46.  
  47. 3rd and 4th steps
  48.  
  49. 1
  50. /
  51. 2 5
  52.  
  53. 6 <--
  54.  
  55. 5th step
  56.  
  57. 1
  58. /
  59. 2 2 <--
  60. /
  61. 5
  62.  
  63. 6
  64.  
  65. 6th step
  66.  
  67. 1
  68. /
  69. 2 2
  70. /
  71. 5 3
  72.  
  73. 6
  74.  
  75. public TreeNode buildTree(int[] inArray){
  76. if (inArray == null || inArray.length == 0) return null;
  77.  
  78. int n = inArray.length;
  79. return dfs(inArray, 0, n - 1);
  80. }
  81.  
  82. private TreeNode dfs(int[] inArray, int start, int end){
  83.  
  84. if (start == end){
  85. return new TreeNode(inArray[start]);
  86. }
  87.  
  88. if (start > end){
  89. return null;
  90. }
  91.  
  92. int minIndex = findMin(inArray, start, end);
  93. TreeNode curNode = new TreeNode(inArray[minIndex]);
  94.  
  95. TreeNode leftNode = dfs(inArray, start, minIndex - 1);
  96. TreeNode rightNode = dfs(inArray, minIndex + 1, right);
  97.  
  98.  
  99. curNode.left = leftNode;
  100.  
  101.  
  102.  
  103. curNode.right = rightNode;
  104.  
  105.  
  106. return curNode;
  107. }
  108.  
  109. private int findMin(int[] inArray, int start, int end){
  110. int minIndex = -1;
  111. int min = Integer.MAX_VALUE;
  112. for (int i = start; i <= end; i++){
  113. if (inArray[i] < min){
  114. minIndex = i;
  115. min = inArray[i];
  116. }
  117. }
  118.  
  119. return minIndex;
  120. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement