Guest User

Untitled

a guest
Jan 17th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6.  
  7.  
  8. class TreeNode {
  9. TreeNode left;
  10. TreeNode right;
  11. String val;
  12.  
  13. public TreeNode(String v) {
  14. left = null;
  15. right = null;
  16. val = v;
  17. }
  18.  
  19. // TODO improvement make this return a status code so we avoid a
  20. // fully linear traversal
  21. public void insertNode(String parent, String l, String r) {
  22. if(this.val == parent) {
  23. this.left = new TreeNode(l);
  24. this.right = new TreeNode(r);
  25. return;
  26. }
  27.  
  28. // Relying here that there are no duplicate keys in the tree
  29. // Problem hasn't specified otherwise
  30. if(this.left != null) {
  31. this.left.insertNode(parent, l, r);
  32. }
  33.  
  34. if(this.right != null) {
  35. this.right.insertNode(parent, l, r);
  36. }
  37.  
  38. return;
  39. }
  40.  
  41. public void printTree() {
  42. System.out.println(this.val);
  43. if(this.left != null) {
  44. this.left.printTree();
  45. }
  46. if(this.right != null) {
  47. this.right.printTree();
  48. }
  49. }
  50. }
  51.  
  52. public class Solution {
  53. public static void main(String args[] ) throws Exception {
  54. Scanner sc = new Scanner(System.in);
  55.  
  56. TreeNode root = null;
  57. int num = 0;
  58. // Read in the tree
  59. while(sc.hasNext()) {
  60. String line = sc.nextLine();
  61.  
  62. String[] tokens = line.split(",");
  63.  
  64. String parent = tokens[0];
  65. if(num == 0) {
  66. root = new TreeNode(parent);
  67. }
  68. String left = tokens[1];
  69. String right = "";
  70.  
  71. // Edge case with how the string.split function works
  72. // Doesn't tokenize a trailing empty token
  73. if(tokens.length > 2) {
  74. right = tokens[2];
  75. }
  76.  
  77. // Find the parent and create the subtree beneath them
  78. root.insertNode(parent, left, right);
  79. num++;
  80. }
  81.  
  82. // FIXME There's a bug with Node insertion.
  83. // Java isn't persisting the value written to a sub-child in memory beyond
  84. //the root node's children so all the data written to the tree is getting lost
  85. //if(root != null) {
  86. // root.printTree();
  87. //}
  88.  
  89. System.out.println(findShallowestDepth(root));
  90. }
  91.  
  92. public static int findShallowestDepth(TreeNode node) {
  93. if(node == null) {
  94. return -1;
  95. } else {
  96. int left = 1 + findShallowestDepth(node.left);
  97. int right = 1 + findShallowestDepth(node.right);
  98.  
  99. return Math.min(left, right);
  100. }
  101. }
  102. }
Add Comment
Please, Sign In to add comment