Binary Tree Vertical Order Traversal code example
Example 1: vertical traversal of binary tree
class Obj
{
public:
Node *root;
int dis;
Obj(Node *node, int dist)
{
root = node;
dis = dist;
}
};
void verticalTraversal(Node *root)
{
queue<Obj*> q;
Obj *ob = new Obj(root, 0);
q.push(ob);
map<int, vector<int>> m;
while(!q.empty())
{
Obj *ob = q.front();
q.pop();
if(m.find(ob->dis) != m.end())
{
m[ob->dis].push_back(ob->root->data);
}
else
{
vector<int> v;
v.push_back(ob->root->data);
m[ob->dis] = v;
}
if(ob->root->left != NULL)
q.push(new Obj(ob->root->left, ob->dis-1));
if(ob->root->right != NULL)
q.push(new Obj(ob->root->right, ob->dis+1));
}
for(auto it=m.begin(); it!=m.end(); it++)
{
vector<int> v1 = (*it).second;
for(int j = 0; j<v1.size(); j++)
cout << v1[j] << "\t";
}
cout << endl;
}
Example 2: vertical traversal of binary tree
import java.util.TreeMap;
import java.util.Vector;
import java.util.Map.Entry;
public class VerticalOrderBtree
{
static class Node
{
int key;
Node left;
Node right;
Node(int data)
{
key = data;
left = null;
right = null;
}
}
static void getVerticalOrder(Node root, int hd,
TreeMap<Integer,Vector<Integer>> m)
{
if(root == null)
return;
Vector<Integer> get = m.get(hd);
if(get == null)
{
get = new Vector<>();
get.add(root.key);
}
else
get.add(root.key);
m.put(hd, get);
getVerticalOrder(root.left, hd-1, m);
getVerticalOrder(root.right, hd+1, m);
}
static void printVerticalOrder(Node root)
{
TreeMap<Integer,Vector<Integer>> m = new TreeMap<>();
int hd =0;
getVerticalOrder(root,hd,m);
for (Entry<Integer, Vector<Integer>> entry : m.entrySet())
{
System.out.println(entry.getValue());
}
}
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);
root.right.left.right = new Node(8);
root.right.right.right = new Node(9);
System.out.println("Vertical Order traversal is");
printVerticalOrder(root);
}
}