fork download
  1. class Node {
  2. public Node left;
  3. public int data;
  4. public Node right;
  5.  
  6. public Node(int val) {
  7. this.data = val;
  8. }
  9.  
  10. @Override
  11. public String toString() {
  12. return this.data + "";
  13. }
  14. }
  15.  
  16. class LeftView {
  17.  
  18. public static int maxLevel = 0;
  19.  
  20. public void leftView(Node root, int level) {
  21. if (root == null)
  22. return;
  23.  
  24. if (maxLevel < level) {
  25. System.out.println(root.data);
  26. maxLevel = level;
  27. }
  28.  
  29. leftView(root.left, level + 1);
  30. leftView(root.right, level + 1);
  31. }
  32.  
  33. public static void main(String[] args) {
  34. Node root = new Node(1);
  35. root.left = new Node(2);
  36. root.left.left = new Node(4);
  37. root.left.right = new Node(5);
  38. root.left.right.left = new Node(7);
  39. root.left.right.right = new Node(8);
  40. root.left.right.left.left = new Node(9);
  41.  
  42. root.right = new Node(3);
  43. root.right.left = new Node(6);
  44. root.right.right = new Node(7);
  45.  
  46. LeftView obj = new LeftView();
  47. obj.leftView(root, 1);
  48. }
  49. }
  50.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
1
2
4
7
9