fork download
  1. import java.util.LinkedList;
  2. class Node {
  3. public Node left;
  4. public int data;
  5. public Node right;
  6.  
  7. public Node(int val) {
  8. this.data = val;
  9. }
  10.  
  11. @Override
  12. public String toString() {
  13. return this.data + "";
  14. }
  15. }
  16.  
  17. class LeftView {
  18.  
  19. public void leftViewQueue(Node root) {
  20.  
  21. boolean isFirstNode = false;
  22. LinkedList<Node> queue = new LinkedList<Node>();
  23.  
  24. queue.addLast(root); //enqueue
  25. queue.addLast(null); //enqueue
  26.  
  27. System.out.print(root.data + "\t");
  28. while (!queue.isEmpty()) {
  29. Node poped = queue.removeFirst(); //dequeue
  30.  
  31. if (poped == null) {
  32. isFirstNode = true; //current level processed , push null for next level
  33. queue.addLast(null);
  34. }
  35. else {
  36.  
  37. if(isFirstNode == true)
  38. {
  39. System.out.print(poped.data + "\t"); // Print first Node
  40. isFirstNode = false; //and set flag to be false until next null encountered
  41. }
  42.  
  43. if (poped.left != null)
  44. queue.addLast(poped.left);
  45. if (poped.right != null)
  46. queue.addLast(poped.right);
  47. }
  48. }
  49. }
  50.  
  51. public static void main(String[] args) {
  52. Node root = new Node(1);
  53. root.left = new Node(2);
  54. root.left.left = new Node(4);
  55. root.left.right = new Node(5);
  56. root.left.right.left = new Node(7);
  57. root.left.right.right = new Node(8);
  58. root.left.right.left.left = new Node(9);
  59.  
  60. root.right = new Node(3);
  61. root.right.left = new Node(6);
  62. root.right.right = new Node(7);
  63.  
  64. LeftView obj = new LeftView();
  65.  
  66. obj.leftViewQueue(root);
  67. }
  68. }
  69.  
Runtime error #stdin #stdout #stderr 4.98s 380224KB
stdin
Standard input is empty
stdout
1	2	4	7	9	
stderr
/spoj/java_run: line 9: 10794 CPU time limit exceeded /opt/$VER/bin/java -client -Xmx256M -Xms16M -Xbatch -Dfile.encoding=UTF-8 -jar tested.zip