You are on page 1of 27

Trees 2

-Priyansh Agarwal
BFS Traversal in a Tree Es
BAS Depth
first fint
Breadth
Search
Sparch

Nodes are numbered in the order in which they are visited


gas
-
I ⑧
234
-
423

old!
Y

!6 dl
vis[1,4,2,3

%
!6 dl
BFS:48
-
8.
-0
BFS Traversal in a Tree
125
idj
Implementation:
quire

⑧ 13
d
&

-- 1 =
=

-- 5y
[
7)
visit+)+
Ad
8. E

- -

- -

·
Time Complexity: O(N)
Diameter of a Tree
Diameter of a tree =
Maximum distance
between any 2 nodes in
the tree

Problem: Link
yawn
·

I do
①Picka random noce X from
the tree v
-
② Do DAS from X and find

E
a

the node with manimum

distance from X
and call y
it
onl
-
~
③ Do a dts from Y and

find mode
the with man

distance from y call it

dist(4,2) diameter
=
-dis te ne
3
X =
-
-
1
y
=

-
11 16
15 12 13 14
di
7 ②
os
~ded!
di
d.
·
. .
12 13
11 15 14 7 ②
16
Proof 2,0) 1

-
-
·⑧ 14

-

I
% =do 12 I
4 15 16

Di from a random node Xthe


3

node which has the


man distance from
will always be end
the point
+
--
-
2

①8
⑳- oo-

X Y
from node the farthest
every
node will be one of the

and points of diameter


the

0(n) dinter
v ~
⑦-
0 (n)
Y 2 0 (n)
of a diameter the tree
% ⑧o
-
dd
-d d bd
zoos N
.d bis
0 12 13 14
Ancestor - Descendant Problem
Given a rooted tree with N nodes and Q queries.

For each query of the form X, Y check whether X is an ancestor of Y or not

N.
N <= 1e5, Q <=
==
1e5 OX
·
x, 4
-

n
X, Y

an of y
ancestor
X is

if 12a(X, y) X
=

common
lowest concestor
-68 d
x, Y

2
b
-
3
4
20/0s X, Y0(N)
-
-
-

0(1)
obd
-

346'6 I
9
7
-

-
>

>
(10)

(0)
10
1- (2,3,4,5
5 ->
(9,10,7,0) 6,1,0,3
Random Terms
-

-
In - Out Time trick 127

Do a DFS traversal. I
2
Store the following information for each node: 1423
1213
First visited time = In time 30 9 10

Last visited time = out time 15 20


2122
4567
16K 18 19

Can you solve the ancestor descendant problem now?


goto
In - Out Time trick
Solving the ancestor - descendant problem:

If X is an ancestor of Y

]= Xin time < Yin time < Yout time < Xout time

You might also like