Skip to content

Commit ebfa937

Browse files
committed
pb8
1 parent aa980ea commit ebfa937

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

pb8/Problem.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
```

pb8/answer.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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));

0 commit comments

Comments
 (0)