|
| 1 | +// 662. Maximum Width of Binary Tree |
| 2 | +//🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/maximum-width-of-binary-tree/ |
| 5 | +// |
| 6 | +// Tags: Tree - Depth-First Search - Breadth-First Search - Binary Tree |
| 7 | + |
| 8 | +use std::{borrow::Borrow, cell::RefCell, collections::VecDeque, rc::Rc}; |
| 9 | + |
| 10 | +// Definition for a binary tree node. |
| 11 | +#[derive(Debug, PartialEq, Eq)] |
| 12 | +pub struct TreeNode { |
| 13 | + pub val: i32, |
| 14 | + pub left: Option<Rc<RefCell<TreeNode>>>, |
| 15 | + pub right: Option<Rc<RefCell<TreeNode>>>, |
| 16 | +} |
| 17 | + |
| 18 | +impl TreeNode { |
| 19 | + #[inline] |
| 20 | + pub fn new(val: i32) -> Self { |
| 21 | + TreeNode { |
| 22 | + val, |
| 23 | + left: None, |
| 24 | + right: None, |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | +struct Solution; |
| 29 | +impl Solution { |
| 30 | + /// Use breadth-first search, visit all the nodes in one level enqueueing |
| 31 | + /// children that are not null together with the index they would be at |
| 32 | + /// inside their own level, after processing each level, check the index |
| 33 | + /// difference between the left and right-most nodes and use that to compute |
| 34 | + /// the result. |
| 35 | + /// |
| 36 | + /// Time complexity: O(n) - We will visit all nodes in the tree but will not |
| 37 | + /// do any work for positions that hold a None value. |
| 38 | + /// Space complexity: O(n) - The queue will hold one entire level which |
| 39 | + /// could be n/2 in size. |
| 40 | + /// |
| 41 | + /// Runtime 2 ms Beats 50% |
| 42 | + /// Memory 2.4 MB Beats 83.33% |
| 43 | + pub fn width_of_binary_tree(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { |
| 44 | + let mut q = VecDeque::from([(root.unwrap(), 0)]); |
| 45 | + let mut res = 1; |
| 46 | + while !q.is_empty() { |
| 47 | + // Process the current level. |
| 48 | + res = res.max(1 + q.back().unwrap().1 - q.front().unwrap().1); |
| 49 | + for _ in 0..q.len() { |
| 50 | + let (rc, idx) = q.pop_front().unwrap(); |
| 51 | + // Push the children to the back of the queue by cloning the |
| 52 | + // Rc I believe this clones a pointer and is cheap. |
| 53 | + if let Some(left) = rc.as_ref().borrow().left.clone() { |
| 54 | + q.push_back((left, idx * 2)); |
| 55 | + }; |
| 56 | + if let Some(right) = rc.as_ref().borrow().right.clone() { |
| 57 | + q.push_back((right, idx * 2 + 1)); |
| 58 | + }; |
| 59 | + } |
| 60 | + } |
| 61 | + res |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +// Tests. |
| 66 | +fn main() { |
| 67 | + println!("\x1b[92m» No tests for this file\x1b[0m") |
| 68 | +} |
0 commit comments