Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Maximum Difference Between Node and Ancestor
Bookmark
Brute Force
Track Min/Max
Input
Example 1
Example 2
Balanced Tree
Custom
tree
=
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13]
8
3
10
1
6
14
4
7
13
max diff = 0
for each node, check
every ancestor
8
3
10
1
6
14
4
7
13
max diff = 0
for each node, check
every ancestor
8
3
10
1
6
14
4
7
13
max diff = 5
at
1
: compare against its ancestors
8
3
10
1
6
14
4
7
13
max diff = 7
backtrack, pop
1
: ancestors = [8, 3]
4
8
3
10
1
6
14
4
7
13
max diff = 7
|4 - 8| = 4
, max stays 7
8
3
10
1
6
14
4
7
13
max diff = 7
backtrack, pop
4
: ancestors = [8, 3, 6]
8
3
10
1
6
14
4
7
13
max diff = 7
null node: return
8
3
10
1
6
14
4
7
13
max diff = 7
append
10
: ancestors = [8, 10]
8
3
10
1
6
14
4
7
13
max diff = 7
at
13
: compare against its ancestors
8
3
10
1
6
14
4
7
13
max diff = 7
null node: return
8
3
10
1
6
14
4
7
13
max diff = 7
return 7
algo
master
.
io
Step:
Start a DFS from the root with an empty ancestors list, maxDiff = 0
0 / 55
Input
Example 1
Example 2
Balanced Tree
Custom
tree
=
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13]
0 / 55
algo
master
.
io
Step:
Start a DFS from the root with an empty ancestors list, maxDiff = 0