-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum_depth_of_binary_tree.rs
89 lines (71 loc) · 2 KB
/
maximum_depth_of_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
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
#![allow(dead_code)]
use std::cell::RefCell;
use std::rc::Rc;
type Tree = Option<Rc<RefCell<TreeNode>>>;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Tree,
pub right: Tree,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
pub fn max_depth(root: Tree) -> i32 {
if root.is_none() {
return 0;
}
let left_depth = max_depth(root.as_ref().unwrap().borrow().left.clone());
let right_depth = max_depth(root.as_ref().unwrap().borrow().right.clone());
return 1 + std::cmp::max(left_depth, right_depth);
}
/*
Algorithm - Recursive DFS (Depth First Search)
- If the root is None, return 0
- Get the max depth of the left subtree
- Get the max depth of the right subtree
- Return 1 + the max of the left and right subtree
Complexity
- Time: O(n)
- Space: O(n)
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
let mut root = TreeNode::new(3);
let mut left = TreeNode::new(9);
let right = TreeNode::new(20);
let left_left = TreeNode::new(15);
let left_right = TreeNode::new(7);
left.left = Some(Rc::new(RefCell::new(left_left)));
left.right = Some(Rc::new(RefCell::new(left_right)));
root.left = Some(Rc::new(RefCell::new(left)));
root.right = Some(Rc::new(RefCell::new(right)));
assert_eq!(max_depth(Some(Rc::new(RefCell::new(root)))), 3);
}
#[test]
fn test_2() {
let mut root = TreeNode::new(1);
let left = TreeNode::new(2);
root.left = Some(Rc::new(RefCell::new(left)));
assert_eq!(max_depth(Some(Rc::new(RefCell::new(root)))), 2);
}
#[test]
fn test_3() {
let root = TreeNode::new(0);
assert_eq!(max_depth(Some(Rc::new(RefCell::new(root)))), 1);
}
#[test]
fn test_4() {
assert_eq!(max_depth(None), 0);
}
}