-
Notifications
You must be signed in to change notification settings - Fork 9
/
univalued_binary_tree.rs
44 lines (39 loc) · 1.07 KB
/
univalued_binary_tree.rs
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
//! https://leetcode.com/problems/univalued-binary-tree/
use super::prelude::*;
fn is_unival_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
match root {
Some(root) => {
let root = root.borrow();
if !is_unival_tree(root.left.clone()) {
return false;
}
if !is_unival_tree(root.right.clone()) {
return false;
}
if let Some(ref child) = root.left {
if root.val != child.borrow().val {
return false;
}
}
if let Some(ref child) = root.right {
if root.val != child.borrow().val {
return false;
}
}
true
}
None => true,
}
}
#[test]
fn test_is_unival_tree() {
for (tree, is_unival) in [
(vec![1, 1, 1, 1, 1, null, 1], true),
(vec![2, 2, 2, 5, 2], false),
] {
assert_eq!(
is_unival_tree(deserialize_vec_to_binary_tree(&tree)),
is_unival
);
}
}