Skip to content

Commit f5c5271

Browse files
committed
solve #104
1 parent 26c3859 commit f5c5271

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,4 @@ mod n0100_same_tree;
104104
mod n0101_symmetric_tree;
105105
mod n0102_binary_tree_level_order_traversal;
106106
mod n0103_binary_tree_zigzag_level_order_traversal;
107+
mod n0104_maximum_depth_of_binary_tree;
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* [104] Maximum Depth of Binary Tree
3+
*
4+
* Given a binary tree, find its maximum depth.
5+
*
6+
* The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
7+
*
8+
* Note: A leaf is a node with no children.
9+
*
10+
* Example:
11+
*
12+
* Given binary tree [3,9,20,null,null,15,7],
13+
*
14+
*
15+
* 3
16+
* / \
17+
* 9 20
18+
* / \
19+
* 15 7
20+
*
21+
* return its depth = 3.
22+
*
23+
*/
24+
pub struct Solution {}
25+
use super::util::tree::{TreeNode, to_tree};
26+
27+
// submission codes start here
28+
29+
use std::rc::Rc;
30+
use std::cell::RefCell;
31+
impl Solution {
32+
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
33+
let mut max = 0;
34+
Solution::depth_helper(root.as_ref(), &mut max, 0);
35+
max
36+
}
37+
38+
fn depth_helper(root: Option<&Rc<RefCell<TreeNode>>>, max: &mut i32, curr: i32) {
39+
if let Some(node) = root {
40+
*max = i32::max(*max, curr + 1);
41+
Solution::depth_helper(node.borrow().left.as_ref(), max, curr + 1);
42+
Solution::depth_helper(node.borrow().right.as_ref(), max, curr + 1);
43+
}
44+
}
45+
}
46+
47+
// submission codes end
48+
49+
#[cfg(test)]
50+
mod tests {
51+
use super::*;
52+
53+
#[test]
54+
fn test_104() {
55+
assert_eq!(Solution::max_depth(tree![]), 0);
56+
assert_eq!(Solution::max_depth(tree![3,9,20,null,null,15,7]), 3);
57+
}
58+
}

0 commit comments

Comments
 (0)