File tree Expand file tree Collapse file tree 2 files changed +71
-0
lines changed Expand file tree Collapse file tree 2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ > This problem was asked by Google.
2
+
3
+ A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
4
+ Given the root to a binary tree, count the number of unival subtrees.
5
+ For example, the following tree has 5 unival subtrees:
6
+
7
+ ```
8
+ 0
9
+ / \
10
+ 1 0
11
+ / \
12
+ 1 0
13
+ / \
14
+ 1 1
15
+ ```
Original file line number Diff line number Diff line change
1
+
2
+ class Node {
3
+ constructor ( val , left = null , right = null ) {
4
+ this . val = val ;
5
+ this . left = left ;
6
+ this . right = right ;
7
+ }
8
+ }
9
+
10
+ // Same tree as example
11
+ const tree = new Node ( 0 ,
12
+
13
+ new Node ( 1 ) , new Node ( 0 ,
14
+
15
+ new Node ( 1 , // 0
16
+
17
+ 1 , 1 ) , new Node ( 0 ) ) ) ;
18
+
19
+
20
+
21
+ const countUnival = ( root ) => {
22
+ let nbUnival = 0 ;
23
+
24
+ const processNode = ( node , value ) => {
25
+
26
+ if ( node . right || node . left ) {
27
+ if ( node . right ) {
28
+ if ( node . right . val === value ) {
29
+ if ( processNode ( node . right , value ) ) {
30
+ nbUnival ++ ;
31
+ }
32
+ } else {
33
+ return processNode ( node . right , value ) ;
34
+ }
35
+ }
36
+
37
+ if ( node . left ) {
38
+ if ( node . left . val === value ) {
39
+ if ( processNode ( node . left , value ) ) {
40
+ nbUnival ++ ;
41
+ }
42
+ } else {
43
+ return processNode ( node . left , value ) ;
44
+ }
45
+ }
46
+
47
+ } else {
48
+ nbUnival ++ ;
49
+ return true ;
50
+ }
51
+ }
52
+ processNode ( root , root . val ) ;
53
+ return nbUnival ;
54
+
55
+ }
56
+ console . log ( countUnival ( tree ) ) ;
You can’t perform that action at this time.
0 commit comments