-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
44 lines (43 loc) · 1.48 KB
/
solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor (val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val === undefined ? 0 : val);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
}
function countUnivalSubtrees (root: TreeNode | null): number {
let result = 0;
function postOrder (root:TreeNode):[boolean, number] {
if (root.left && root.right) {
const [leftIs, leftVal, ] = postOrder(root.left);
const [rightIs, rightVal, ] = postOrder(root.right);
if (!leftIs || !rightIs || root.val !== leftVal || root.val !== rightVal) {
return [false, 0, ];
}
result++;
return [true, root.val, ];
} else if (root.left) {
const [leftIs, leftVal, ] = postOrder(root.left);
if (!leftIs || root.val !== leftVal) {
return [false, 0, ];
}
result++;
return [true, root.val, ];
} else if (root.right) {
const [rightIs, rightVal, ] = postOrder(root.right);
if (!rightIs || root.val !== rightVal) {
return [false, 0, ];
}
result++;
return [true, root.val, ];
} else {
result++;
return [true, root.val, ];
}
}
root && postOrder(root);
return result;
}