题解 | #求二叉树的层序遍历# | Rust
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
/** * #[derive(PartialEq, Eq, Debug, Clone)] * pub struct TreeNode { * pub val: i32, * pub left: Option<Box<TreeNode>>, * pub right: Option<Box<TreeNode>>, * } * * impl TreeNode { * #[inline] * fn new(val: i32) -> Self { * TreeNode { * val: val, * left: None, * right: None, * } * } * } */ struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型二维数组 */ pub fn levelOrder(&self, root: Option<Box<TreeNode>>) -> Vec<Vec<i32>> { let mut ans : Vec<Vec<i32>> = Vec::new(); if let Some(root) = root { let mut queue : VecDeque<Box<TreeNode>> = VecDeque::new(); queue.push_back(root); while !queue.is_empty() { let mut n = queue.len(); let mut item : Vec<i32> = Vec::new(); for i in 0..n { if let Some(node) = queue.pop_front() { item.push(node.val); if let Some(l) = node.left { queue.push_back(l); } if let Some(r) = node.right { queue.push_back(r); } } } ans.push(item); } } return ans; } }