Advertisement
Checosnake

Solution 2 java

Oct 22nd, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. package com.google.challenges;
  2. import java.util.Stack;
  3.  
  4. public class Answer {
  5. static class BinTree {
  6. int total;
  7. int[] nodes;
  8. Stack<Integer> values = new Stack();
  9. BinTree(int x) {
  10. total = (int) Math.pow(2, x) - 1;
  11. nodes = new int[total];
  12. //Populate Nodes List
  13. for (int i = 0, j = total; i < total; i++, j--) {
  14. nodes[i] = -2;
  15. values.add(j);
  16. }
  17. postOrder(0);
  18. }
  19. int eval(int i) {
  20. if ( i == -1)
  21. {
  22. return -1;
  23. }
  24. if (i > total-1)
  25. {
  26. return -1;
  27. }
  28. else
  29. {
  30. return nodes[i];
  31. }
  32. }
  33. boolean hasChild(int i) {
  34. int l = Lchild(i);
  35. int r = Rchild(i);
  36. if (l > total - 1 && r > total - 1) {
  37. return false;
  38. }
  39. else
  40. {
  41. return true;
  42. }
  43. }
  44. void populateNode(int i){
  45. int v = values.pop();
  46. nodes[i] = v;
  47. }
  48. void postOrder(int i){
  49. if (!hasChild(i))
  50. {
  51. populateNode(i);
  52. }
  53. else
  54. {
  55. postOrder(Lchild(i));
  56. postOrder(Rchild(i));
  57. populateNode(i);
  58. }
  59. }
  60. int Lchild(int i) {
  61. return(i*2)+1;
  62. }
  63. int Rchild(int i){
  64. return(i+1)*2;
  65. }
  66. }
  67. public static int parentIndex(int i) {
  68. int p =(i-1)/2;
  69. if(i == 0)
  70. {
  71. return -1;
  72. }
  73. else{
  74. return p;
  75. }
  76. }
  77. public static int find(int[]array, int x){
  78. for(int i = 0; i<array.length; i++)
  79. {
  80. if (array[i] == x)
  81. {
  82. return i;
  83. }
  84. }
  85. return -1;
  86. }
  87. public static int[] answer(int h, int[] q) {
  88. BinTree tree = new BinTree(h);
  89. int rootVal = tree.nodes[0];
  90. int[] output = new int[q.length];
  91. int[] temp = new int[q.length];
  92. for (int i =0; i < q.length; i++)
  93. {
  94. temp[i] = parentIndex(find(tree.nodes, q[i]));
  95. }
  96. for (int i =0; i < q.length; i++)
  97. {
  98. output[i] = tree.eval(temp[i]);
  99. }
  100. delete tree;
  101. return output;
  102. }
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement