题解 | #把二叉树打印成多行# | Rust
把二叉树打印成多行
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
/** * #[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 pRoot TreeNode类 * @return int整型二维数组 */ pub fn Print(&self, pRoot: Option<Box<TreeNode>>) -> Vec<Vec<i32>> { let mut ans = Vec::new(); if let Some(mut root) = pRoot { 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::new(); for i in 0..n { let mut node = queue.pop_front().unwrap(); item.push(node.val); if node.left.is_some() { queue.push_back(node.left.unwrap()); } if node.right.is_some() { queue.push_back(node.right.unwrap()); } } ans.push(item); } } return ans; } }