Last active
September 28, 2018 18:19
-
-
Save thmain/8e80b5d7a7b20bdf05a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Set; | |
import java.util.TreeMap; | |
public class VerticalOrder { | |
public static TreeMap<Integer, ArrayList> ht = new TreeMap<>(); | |
public ArrayList<Integer> al; | |
public void vertical(Node root, int level) { | |
if (root == null) { | |
return; | |
} | |
if (ht.containsKey(level)) { | |
ArrayList x = ht.get(level); | |
x.add(root.data); | |
ht.put(level, x); | |
} else { | |
al = new ArrayList<>(); | |
al.add(root.data); | |
ht.put(level, al); | |
} | |
vertical(root.left, level-1); | |
vertical(root.right, level+1); | |
} | |
public void printResult(TreeMap ht) { | |
Set<Integer> i = ht.keySet(); | |
for (int keys : i) { | |
System.out.println(ht.get(keys)); | |
} | |
} | |
public static void main(String args[]) { | |
Node root = new Node(1); | |
root.left = new Node(2); | |
root.right = new Node(3); | |
root.left.left = new Node(4); | |
root.left.right = new Node(5); | |
root.right.left = new Node(6); | |
root.right.right = new Node(7); | |
VerticalOrder p = new VerticalOrder(); | |
p.vertical(root, 0); | |
p.printResult(ht); | |
} | |
} | |
class Node { | |
int data; | |
Node left; | |
Node right; | |
public Node(int data) { | |
this.data = data; | |
left = null; | |
right = null; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment