Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print the given binary tree in vertical order
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.lang.reflect.Array;
- import java.util.*;
- import static java.lang.Integer.max;
- // node class
- class node{
- int data;
- int hd;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.hd = -1;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to print the nodes of the binary tree in vertical order
- // using horizontal distance of a node from the root node
- static void vertical_order(node root){
- if(root == null){
- return;
- }
- // initialize a map and queue
- // we will use iterative BFS traversal to solve this
- Map M = new HashMap<Integer, Integer>();
- ArrayList<ArrayList<Integer>> A = new ArrayList();
- ArrayList Q = new ArrayList<node>();;
- // push root in queue and initialize horizontal distance
- Q.add(root);
- int horizontal_distance = root.hd;
- while(!Q.isEmpty()){
- node current = (node)Q.get(0);
- Q.remove(0);
- if(M.containsKey(current.hd)){
- int index = (int)M.get(current.hd);
- A.get(index).add(current.data);
- }else{
- A.add(new ArrayList<>());
- int index = A.size() - 1;
- A.get(index).add(current.data);
- M.put(current.hd, index);
- }
- // update horizontal distance of the left child and put it in the queue
- if(current.left != null){
- current.left.hd = current.hd - 1;
- Q.add(current.left);
- }
- // update horizontal distance of the right child and put it in the queue
- if(current.right != null) {
- current.right.hd = current.hd + 1;
- Q.add(current.right);
- }
- }
- List<Integer> a = new ArrayList<>(M.keySet());
- for(int hd:a){
- int index = (int)M.get(hd);
- System.out.println("Nodes at horizontal distance " + hd + " are : " + A.get(index));
- }
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- head.hd = 0;
- System.out.println("Vertical order traversal of the given tree is : ");
- vertical_order(head);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment