Guest User

Untitled

a guest
May 22nd, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. 1.
  2. A tree, (NOT NECESSARILY BINARY), has nodes numbered 0 to N-1. An array has indices ranging from 0 to N-1.
  3. The indices denote the node ids and values denote the ids of parents. A value of -1 at some index k denotes
  4. that node with id k is the root. For ex:
  5.  
  6.  
  7. 3 3 3 -1 2
  8. 0 1 2 3 4
  9. In the above, nodes with ids 0, 1 & 2 have 3 as parent. 3 is the root as its parent = -1 and 2 is the parent of node id 4.
  10.  
  11. Given such an array, find the heig ht of the tree.
  12.  
  13. keyword:
  14.  
  15. a tree - children maybe > 2
  16. 0 - N - 1, total N nodes
  17. customize array[i] - i - node id, array[i] is node id i's parent
  18. -1 is special: root node
  19.  
  20. ask: given such an array, find the hight of the tree
  21.  
  22. 3 3 3 -1 2
  23. 0 1 2 3 4
  24. reconstruct:
  25. parent <- child
  26. 3 <- 0
  27. 3 <- 1
  28. 3 <- 2
  29. -1 <- 3 root
  30. 2 <- 4
  31. above height of tree is 3
  32. 0 -> 3 -> -1 -> 0 -> height[0] = 2, height[3] = 1,
  33. 1 -> 3 -> -1 -> 1 + height[3] = 2
  34. 2 -> 3 -> - 1 -> 1 + height[3] = 2
  35. 3 -> -1
  36. 4 -> 2 -> 3-> -1
  37. line 36 -> 3 brute force solution O(n * height of tree)
  38. line 34, 2 -> 3
  39.  
  40. public static int FindHeightOfTree(int[] numbers) // indexWithParentId
  41. {
  42. if(numbers == null)
  43. return new int[0];
  44.  
  45. var length = numbers.Length;
  46.  
  47. var heightIds = new int[length];
  48. for(int index = 0; index < length; index++)
  49. {
  50. if(heightIds[index] > 0)
  51. continue;
  52.  
  53. // find the path for id = index, save height along the path for each id
  54. //3 3 3 -1 2
  55. //0 1 2 3 4
  56. var iterate = index; // 0
  57. var pathLength = 0;
  58. var pathList = new List<int>();
  59. // index = 3
  60. // iterate = index = 3
  61. // numbers[iterate] = -1
  62. while(iterate != -1) // deadloop - no problem ->
  63. {
  64. var visit = numbers[iterate]; // 3
  65. iterate = visit; // 3
  66.  
  67. // height -> no more loop -> exit
  68. if(height[visit] > 0) //
  69. {
  70. pathLength += height[visit];
  71. break;
  72. }
  73.  
  74. pathList.Add(visit); // 3
  75. pathLength++;
  76. }
  77.  
  78. // add one more while loop -> replace the list
  79.  
  80. heightIds[index] = pathLength;
  81. for(int i = 0; i < pathList.Length; i++)
  82. {
  83. if(height[pathList[i]] != 0) // duplicate -> more than O(n)
  84. height[pathList[i]] = pathLength - i;
  85. }
  86. }
  87.  
  88. return heightIds.Max();
  89. }
  90.  
  91.  
  92. -1 0 1 2 3
  93. 0 1 2 3 4
  94.  
  95. 0 - > -1
  96. 1 -> 0 -> -1
  97. 2 -> 1 -> look up height
  98. 3 -> 2 -> look up height
  99. 4->3 -> look up height
Add Comment
Please, Sign In to add comment