Advertisement
thewitchking

Untitled

May 23rd, 2025
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. // Online Java Compiler
  2. // Use this editor to write, compile and run your Java code online
  3.  
  4. // Java program to print corner node at each level in a binary tree
  5.  
  6. import java.util.*;
  7. class Node
  8. {
  9.     int key;
  10.     Node left, right;
  11.  
  12.     public Node(int key)
  13.     {
  14.         this.key = key;
  15.         left = right = null;
  16.     }
  17. }
  18.  
  19. class Main
  20. {
  21.     Node root;
  22.     void printCorner(Node root)
  23.     {
  24.         Queue<Node> q = new LinkedList<Node>();
  25.         q.add(root);
  26.         while (!q.isEmpty())
  27.         {
  28.             int n = q.size();
  29.             for(int i = 0 ; i < n ; i++){
  30.             Node temp = q.peek();
  31.             q.poll();
  32.             if(i==0 || i==n-1)
  33.                 System.out.print(temp.key + "  ");
  34.             if (temp.left != null)
  35.                 q.add(temp.left);
  36.             if (temp.right != null)
  37.                 q.add(temp.right);
  38.         }
  39.         }
  40.  
  41.     }
  42.  
  43.     public static void main(String[] args)
  44.     {
  45.         Main tree = new Main();
  46.         tree.root = new Node(1);
  47.         tree.root.left = new Node(2);
  48.         tree.root.right = new Node(3);
  49.         tree.root.left.left = new Node(4);
  50.         tree.root.left.right = new Node(5);
  51.         tree.root.right.left = new Node(7);
  52.         tree.root.right.right = new Node(6);
  53.  
  54.         tree.printCorner(tree.root);
  55.     }
  56. }
  57.  
  58. // This code has been contributed by Utkarsh Choubey
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement