0104 - Maximum Depth of Binary Tree
description
Given the root
of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:

Input: root = [3,9,20,null,null,15,7] Output: 3
Example 2:
Input: root = [1,null,2] Output: 2
Constraints:
- The number of nodes in the tree is in the range
[0, 104]
. -100 <= Node.val <= 100
submission
// 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
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
// double queue
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let (mut dq, mut swp) = (Vec::new(), Vec::new());
let mut ans = 0;
// setup, add the first node to queue
if let Some(root) = root {
dq.push(root);
};
// outer loop
while !dq.is_empty() {
// we setup the inner loop here, like sum
ans += 1;
while let Some(node) = dq.pop() {
let node = node.borrow();
if let Some(ref n) = node.left {
swp.push(n.clone());
}
if let Some(ref n) = node.right {
swp.push(n.clone());
}
}
// alternate between two queues
std::mem::swap(&mut dq, &mut swp);
}
ans
}
}