Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- import java.text.*;
- import java.math.*;
- import java.util.regex.*;
- class TreeNode {
- TreeNode left;
- TreeNode right;
- String val;
- public TreeNode(String v) {
- left = null;
- right = null;
- val = v;
- }
- // TODO improvement make this return a status code so we avoid a
- // fully linear traversal
- public void insertNode(String parent, String l, String r) {
- if(this.val == parent) {
- this.left = new TreeNode(l);
- this.right = new TreeNode(r);
- return;
- }
- // Relying here that there are no duplicate keys in the tree
- // Problem hasn't specified otherwise
- if(this.left != null) {
- this.left.insertNode(parent, l, r);
- }
- if(this.right != null) {
- this.right.insertNode(parent, l, r);
- }
- return;
- }
- public void printTree() {
- System.out.println(this.val);
- if(this.left != null) {
- this.left.printTree();
- }
- if(this.right != null) {
- this.right.printTree();
- }
- }
- }
- public class Solution {
- public static void main(String args[] ) throws Exception {
- Scanner sc = new Scanner(System.in);
- TreeNode root = null;
- int num = 0;
- // Read in the tree
- while(sc.hasNext()) {
- String line = sc.nextLine();
- String[] tokens = line.split(",");
- String parent = tokens[0];
- if(num == 0) {
- root = new TreeNode(parent);
- }
- String left = tokens[1];
- String right = "";
- // Edge case with how the string.split function works
- // Doesn't tokenize a trailing empty token
- if(tokens.length > 2) {
- right = tokens[2];
- }
- // Find the parent and create the subtree beneath them
- root.insertNode(parent, left, right);
- num++;
- }
- // FIXME There's a bug with Node insertion.
- // Java isn't persisting the value written to a sub-child in memory beyond
- //the root node's children so all the data written to the tree is getting lost
- //if(root != null) {
- // root.printTree();
- //}
- System.out.println(findShallowestDepth(root));
- }
- public static int findShallowestDepth(TreeNode node) {
- if(node == null) {
- return -1;
- } else {
- int left = 1 + findShallowestDepth(node.left);
- int right = 1 + findShallowestDepth(node.right);
- return Math.min(left, right);
- }
- }
- }
Add Comment
Please, Sign In to add comment