Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Online Java Compiler
- // Use this editor to write, compile and run your Java code online
- // Java program to print corner node at each level in a binary tree
- import java.util.*;
- class Node
- {
- int key;
- Node left, right;
- public Node(int key)
- {
- this.key = key;
- left = right = null;
- }
- }
- class Main
- {
- Node root;
- void printCorner(Node root)
- {
- Queue<Node> q = new LinkedList<Node>();
- q.add(root);
- while (!q.isEmpty())
- {
- int n = q.size();
- for(int i = 0 ; i < n ; i++){
- Node temp = q.peek();
- q.poll();
- if(i==0 || i==n-1)
- System.out.print(temp.key + " ");
- if (temp.left != null)
- q.add(temp.left);
- if (temp.right != null)
- q.add(temp.right);
- }
- }
- }
- public static void main(String[] args)
- {
- Main tree = new Main();
- tree.root = new Node(1);
- tree.root.left = new Node(2);
- tree.root.right = new Node(3);
- tree.root.left.left = new Node(4);
- tree.root.left.right = new Node(5);
- tree.root.right.left = new Node(7);
- tree.root.right.right = new Node(6);
- tree.printCorner(tree.root);
- }
- }
- // This code has been contributed by Utkarsh Choubey
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement