-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum_depth_of_binary_tree.rs
More file actions
71 lines (61 loc) · 2 KB
/
Copy pathmaximum_depth_of_binary_tree.rs
File metadata and controls
71 lines (61 loc) · 2 KB
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
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use utils::tree_node::TreeNode;
pub struct Solution;
impl Solution {
// Recursive DFS solution
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
match root {
Some(node) => {
let node_borrowed = node.borrow();
1 + cmp::max(
Self::max_depth(node_borrowed.left.clone()),
Self::max_depth(node_borrowed.right.clone()),
)
}
None => 0,
}
}
// Iterative DFS solution
pub fn max_depth_dfs(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if root.is_none() {
return 0;
}
let mut stack = vec![(root, 1)];
let mut max_depth = 0;
while let Some((node_option, depth)) = stack.pop() {
if let Some(node) = node_option {
max_depth = cmp::max(max_depth, depth);
let node_borrowed = node.borrow();
stack.push((node_borrowed.left.clone(), depth + 1));
stack.push((node_borrowed.right.clone(), depth + 1));
}
}
max_depth
}
// Interative BFS solution
pub fn max_depth_bfs(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if root.is_none() {
return 0;
}
let mut queue = std::collections::VecDeque::new();
queue.push_back(root);
let mut depth = 0;
while !queue.is_empty() {
depth += 1;
for _ in 0..queue.len() {
if let Some(Some(node)) = queue.pop_front() {
let node_borrowed = node.borrow();
if node_borrowed.left.is_some() {
queue.push_back(node_borrowed.left.clone());
}
if node_borrowed.right.is_some() {
queue.push_back(node_borrowed.right.clone());
}
}
}
}
depth
}
}