From 0465d255a5ac2a31b8d24412b3da5dd6be664ea9 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 16 Feb 2024 10:28:57 +0800 Subject: [PATCH] 20240216 Finished --- src/problem/mod.rs | 3 +- ...inary_tree_zigzag_level_order_traversal.rs | 84 +++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 src/problem/p103_binary_tree_zigzag_level_order_traversal.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 68c6dc1..172c354 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -48,4 +48,5 @@ mod p144_binary_tree_preorder_traversal; mod p145_binary_tree_postorder_traversal; mod p987_vertical_order_traversal_of_a_binary_tree; mod p102_binary_tree_level_order_traversal; -mod p107_binary_tree_level_order_traversal_ii; \ No newline at end of file +mod p107_binary_tree_level_order_traversal_ii; +mod p103_binary_tree_zigzag_level_order_traversal; \ No newline at end of file diff --git a/src/problem/p103_binary_tree_zigzag_level_order_traversal.rs b/src/problem/p103_binary_tree_zigzag_level_order_traversal.rs new file mode 100644 index 0000000..ac51120 --- /dev/null +++ b/src/problem/p103_binary_tree_zigzag_level_order_traversal.rs @@ -0,0 +1,84 @@ +/** + * [103] Binary Tree Zigzag Level Order Traversal + */ +pub struct Solution {} + +use crate::util::tree::{TreeNode, to_tree}; + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn zigzag_level_order(root: Option>>) -> Vec> { + let root = if let Some(r) = root { + r + } else { + return vec![]; + }; + + let mut result = Vec::new(); + let mut reverse = false; + let mut queue = VecDeque::new(); + queue.push_back(root); + + while !queue.is_empty() { + let mut level = Vec::with_capacity(queue.len()); + for _ in 0..queue.len() { + if let Some(node) = queue.pop_front() { + level.push(node.borrow().val); + + if let Some(left) = &node.borrow().left { + queue.push_back(Rc::clone(left)); + } + + if let Some(right) = &node.borrow().right { + queue.push_back(Rc::clone(right)); + } + } + } + + if reverse { + level.reverse(); + } + reverse = !reverse; + + result.push(level); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_103() { + assert_eq!(Solution::zigzag_level_order( + to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]) + ), vec![vec![3], vec![20, 9], vec![15, 7]]); + } +}