Professional Documents
Culture Documents
-Priyansh Agarwal
BFS Traversal in a Tree Es
BAS Depth
first fint
Breadth
Search
Sparch
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
distance from X
and call y
it
onl
-
~
③ Do a dts from Y and
find mode
the with man
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
①8
⑳- oo-
X Y
from node the farthest
every
node will be one of 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.
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
If X is an ancestor of Y
]= Xin time < Yin time < Yout time < Xout time