-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path250. Count-Univalue-Subtree
56 lines (52 loc) · 1.32 KB
/
250. Count-Univalue-Subtree
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
45
46
47
48
49
50
51
52
53
54
55
56
import {
TreeNode,
} from '/opt/node/lib/lintcode/index.js';
/**
* Definition of TreeNode:
* class TreeNode {
* constructor(val, left=null, right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
export class Solution {
/**
* @param root: the given tree
* @return: the number of uni-value subtrees.
*/
countUnivalSubtrees(root) {
// write your code here
let res = 0
function helper(root){
if(!root)
return [true, -1];
if(root.left == null && root.right == null){
res += 1
return [true, root.val]
}
let [isUniLeft, leftVal] = helper(root.left)
let [isUniRight, rightVal] = helper(root.right)
if(isUniLeft && isUniRight){
if(root.val == leftVal && root.val == rightVal){
res += 1
return [true, root.val]
}else if(leftVal == -1){
if(root.val == rightVal){
res += 1
return [true, root.val]
}
}else if(rightVal == -1){
if(root.val == leftVal){
res += 1
return [true, root.val]
}
}
}
return [false, 0]
}
helper(root);
return res
}
}