-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy patheven-odd-tree.rs
101 lines (96 loc) · 2.89 KB
/
even-odd-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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// 1609. Even Odd Tree
// 🟠 Medium
//
// https://leetcode.com/problems/even-odd-tree/
//
// Tags: Tree - Breadth-First Search - Binary Tree
use std::cell::RefCell;
use std::rc::Rc;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
struct Solution;
impl Solution {
/// Do a double BFS checking each level against the conditions they must satisfy.
///
/// Time complexity: O(n) - BFS, we will visit each node.
/// Space complexity: O(l) - The vectors will grow to the size of the levels they hold.
///
/// Runtime 31 ms Beats 50%
/// Memory 11.7 MB Beats 50%
#[allow(dead_code)]
pub fn is_even_odd_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
let mut even_level = Vec::from([root.unwrap()]);
let mut odd_level = vec![];
let mut last_value: Option<i32>;
loop {
if even_level.is_empty() {
return true;
}
last_value = None;
odd_level.clear();
// Even level: odd increasing values
for rc in &even_level {
let node = rc.borrow();
if node.val % 2 == 0 {
return false;
}
if let Some(last) = last_value {
if last >= node.val {
return false;
}
}
last_value = Some(node.val);
if let Some(left) = &node.left {
odd_level.push(left.clone());
}
if let Some(right) = &node.right {
odd_level.push(right.clone());
}
}
if odd_level.is_empty() {
return true;
}
last_value = None;
even_level.clear();
// Odd level: even decreasing values
for rc in &odd_level {
let node = rc.borrow();
if node.val % 2 == 1 {
return false;
}
if let Some(last) = last_value {
if last <= node.val {
return false;
}
}
last_value = Some(node.val);
if let Some(left) = &node.left {
even_level.push(left.clone());
}
if let Some(right) = &node.right {
even_level.push(right.clone());
}
}
}
}
}
// Tests.
fn main() {
let tests = [(vec![0], 0)];
println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len());
}