Sie sind auf Seite 1von 8

3/23/2014

Print a Binary Tree in Vertical Order | Set 1 | GeeksforGeeks

GeeksforGeeks
A computer science portal for geeks

GeeksQuiz
Login
Home
Algorithms
DS
GATE
Interview Corner
Q&A
C
C++
Java
Books
Contribute
Ask a Q
About
Array
Bit Magic
C/C++
Articles
GFacts
Linked List
MCQ
Misc
Output
String
Tree
Graph

Print a Binary Tree in Vertical Order | Set 1


Given a binary tree, print it vertically. The following example illustrates vertical order traversal.
1
/
\
2
3
/\
/\
4 5 6 7
\ \
8 9

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

1/8

3/23/2014

Print a Binary Tree in Vertical Order | Set 1 | GeeksforGeeks

Teotu o pitti te vrial wl b:


h upt f rn hs re etcly il e
4
2
156
38
7
9

We strongly recommend to minimize the browser and try this yourself first.
The idea is to traverse the tree once and get the minimum and maximum horizontal distance with respect to
root. For the tree shown above, minimum distance is -2 (for node with value 4) and maximum distance is 3
(For node with value 9).
Once we have maximum and minimum distances from root, we iterate for each vertical line at distance
minimum to maximum from root, and for each vertical line traverse the tree and print the nodes which lie on
that vertical line.
Algorithm:
/ mn->Mnmmhrzna dsac fo ro
/ i - iiu oiotl itne rm ot
/ mx->Mxmmhrzna dsac fo ro
/ a - aiu oiotl itne rm ot
/ h ->Hrzna dsac o cretnd fo ro
/ d - oiotl itne f urn oe rm ot
fnMna(re mn mx h)
idiMxte, i, a, d
i te i NL te rtr;
f re s UL hn eun
i h i ls ta mnte
f d s es hn i hn
mn=h;
i
d
es i h i getrta mxte
le f d s rae hn a hn
*a =h;
mx
d
fnMna(re>et mn mx h-)
idiMxte-lf, i, a, d1;
fnMna(re>ih,mn mx h+)
idiMxte-rgt i, a, d1;

pitetcliete,ln_o h)
rnVriaLn(re ien, d
i te i NL te rtr;
f re s UL hn eun
i h i eult ln_o te
f d s qa o ien, hn
pitte-dt)
rn(re>aa;
pitetcliete-lf,ln_o h-)
rnVriaLn(re>et ien, d1;
pitetcliete-rgt ln_o h+)
rnVriaLn(re>ih, ien, d1;

Implementation:
Following is C++ implementation of above algorithm.
#nld <otem
icue isra>
uignmsaesd
sn aepc t;
/ And o bnr te
/
oe f iay re
src Nd
tut oe
{
itdt;
n aa
src Nd *et *ih;
tut oe lf, rgt
}
;
/ Auiiyfnto t cet anwBnr Te nd
/
tlt ucin o rae
e iay re oe
Nd*nwoeitdt)
oe eNd(n aa
http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

2/8

3/23/2014

Print a Binary Tree in Vertical Order | Set 1 | GeeksforGeeks

Nd *ep=nwNd;
oe tm
e oe
tm-dt =dt;
ep>aa
aa
tm-lf =tm-rgt=NL;
ep>et
ep>ih
UL
rtr tm;
eun ep

/ Auiiyfnto t fn mnadmxdsacswt rset


/
tlt ucin o id i n a itne ih epc
/ t ro.
/ o ot
vi fnMna(oe*oe it*i,it*a,ith)
od idiMxNd nd, n mn n mx n d
{
/ Bs cs
/ ae ae
i (oe= NL)rtr;
f nd = UL eun
/ Udt mnadmx
/ pae i n a
i (d<*i) *i =h;
f h
mn
mn
d
es i (d>*a)*a =h;
le f h
mx mx
d

/ Rcrfrlf adrgtsbre
/ eu o et n ih utes
fnMna(oe>et mn mx h-)
idiMxnd-lf, i, a, d1;
fnMna(oe>ih,mn mx h+)
idiMxnd-rgt i, a, d1;

/ Auiiyfnto t pitalndso agvnln_o


/
tlt ucin o rn l oe n
ie ien.
/ h i hrzna dsac o cretnd wt rsett ro.
/ d s oiotl itne f urn oe ih epc o ot
vi pitetclieNd *oe itln_o ith)
od rnVriaLn(oe nd, n ien, n d
{
/ Bs cs
/ ae ae
i (oe= NL)rtr;
f nd = UL eun
/ I ti nd i o tegvnln nme
/ f hs oe s n h ie ie ubr
i (d= ln_o
f h = ien)
cu < nd-dt < ""
ot < oe>aa <
;

/ Rcrfrlf adrgtsbre
/ eu o et n ih utes
pitetcliend-lf,ln_o h-)
rnVriaLn(oe>et ien, d1;
pitetcliend-rgt ln_o h+)
rnVriaLn(oe>ih, ien, d1;

/ Temi fnto ta pit agvnbnr te i


/ h an ucin ht rns
ie iay re n
/ vria odr
/ etcl re
vi vriaOdrNd *ot
od etclre(oe ro)
{
/ Fn mnadmxdsacswt rspc t ro
/ id i n a itne ih eeet o ot
itmn=0 mx=0
n i
, a
;
fnMna(ot &i,&a,0;
idiMxro, mn mx )

/ Ieaetruhalpsil vria lnssatn


/ trt hog l osbe etcl ie trig
/ fo telfms ln adpitndsln b ln
/ rm h etot ie n rn oe ie y ie
fr(n ln_o=mn ln_o< mx ln_o+
o it ien
i; ien = a; ien+)
{
pitetcliero,ln_o 0;
rnVriaLn(ot ien, )
cu < ed;
ot < nl
}

/ Die pormt ts aoefntos


/ rvr rga o et bv ucin
http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

3/8

3/23/2014

Print a Binary Tree in Vertical Order | Set 1 | GeeksforGeeks

itmi(
n an)
{
/ Cet bnr te soni aoefgr
/ rae iay re hw n bv iue
Nd *ot=nwoe1;
oe ro
eNd()
ro-lf =nwoe2;
ot>et
eNd()
ro-rgt=nwoe3;
ot>ih
eNd()
ro-lf-lf =nwoe4;
ot>et>et
eNd()
ro-lf-rgt=nwoe5;
ot>et>ih
eNd()
ro-rgt>et=nwoe6;
ot>ih-lf
eNd()
ro-rgt>ih =nwoe7;
ot>ih-rgt
eNd()
ro-rgt>et>ih =nwoe8;
ot>ih-lf-rgt
eNd()
ro-rgt>ih-rgt=nwoe9;
ot>ih-rgt>ih
eNd()
cu < "etclodrtaesli \"
ot < Vria re rvra s n;
vriaOdrro)
etclre(ot;
}

rtr 0
eun ;

Output:
Vria odrtaesli
etcl re rvra s
4
2
156
38
7
9

Time Complexity: Time complexity of above algorithm is O(w*n) where w is width of Binary Tree and n is
number of nodes in Binary Tree. In worst case, the value of w can be O(n) (consider a complete tree for
example) and time complexity can become O(n2).
This problem can be solved more efficiently using the technique discussed in this post. We will soon be
discussing complete algorithm and implementation of more efficient method.
This article is contributed by Shalki Agarwal. Please write comments if you find anything incorrect, or you
want to share more information about the topic discussed above

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

4/8

3/23/2014

Print a Binary Tree in Vertical Order | Set 1 | GeeksforGeeks

Related Tpoics:
Interval Tree
Check if a given Binary Tree is height balanced like a Red-Black Tree
Print all nodes that are at distance k from a leaf node
Find distance between two given keys of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1
Print all nodes that dont have sibling
Convert a given Binary Tree to Doubly Linked List | Set 3
Red-Black Tree | Set 2 (Insert)
Like

12

Tw eet

Writing code in comment? Please use ideone.com and share the link here.
3 Comments

GeeksforGeeks

Sort by Newest

Login
Share

Favorite

Join the discussion


Suman

a day ago

java code that uses hashmap


http://ideone.com/J2Inia
Reply Share

Chirag

3 days ago

C++ code using map and vector


Time Complexity : O(n) , Space Complexity : O(n)
http://ideone.com/wIZrLt
1
dhruv

Reply Share

3 days ago

if we use a hashmap with key as distance and value as linked list having nodes with key as
distance from root , we restrict it to O(n) time complexity but with space complexity
increased.
1

Subscribe

Reply Share

Add Disqus to your site

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

5/8

3/23/2014

Print a Binary Tree in Vertical Order | Set 1 | GeeksforGeeks

Interview Experiences
Advanced Data Structures
Dynamic Programming
Greedy Algorithms
Backtracking
Pattern Searching
Divide & Conquer
Mathematical Algorithms
Recursion
Geometric Algorithms

Popular Posts
All permutations of a given string
Memory Layout of C Programs
Understanding extern keyword in C
Median of two sorted arrays
Tree traversal without recursion and without stack!
Structure Member Alignment, Padding and Data Packing
Intersection point of two Linked Lists
Lowest Common Ancestor in a BST.
Check if a binary tree is BST or not
Sorted Linked List to Balanced BST

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

6/8

3/23/2014

Print a Binary Tree in Vertical Order | Set 1 | GeeksforGeeks

Subscribe

Recent Comments
Guest
.Suman , can you explain what will be returned...
Print all nodes that are at distance k from a leaf node 5 minutes ago
Aditya Joshi
Finding the inorder sucessor can be rephrased...
Amazon Interview | Set 71 (For SDE-2) 6 minutes ago
anonymous

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

7/8

3/23/2014

Print a Binary Tree in Vertical Order | Set 1 | GeeksforGeeks

In the first instance, 4 is neither a majority...


Majority Element 3 hours ago
sunil
This is the same question as the diameter question
Find distance between two given keys of a Binary Tree 4 hours ago
Suraj K
@geeksforgeeks:disqus Answer should be 7MSS as...
Computer Networks | Set 2 4 hours ago
piyush.ag
A better way :: int kDistanceChildNode(Node...
Find distance between two given keys of a Binary Tree 5 hours ago

C++ Example
Binary Tree
Tree Root

Graph C++
Ancestor Tree
Vertical

Node
Java C++
C++ Source Code

@geeksforgeeks, Some rights reserved


Contact Us!
Powered by WordPress & MooTools, customized by geeksforgeeks team

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

8/8

Das könnte Ihnen auch gefallen