题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
rust代码没有通过,感觉是用例问题,但是不通过用例没有给出完整的输入和输出,因为输出太长了
/**
* #[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 PrintFromTopToBottom(&self, root: Option<Box<TreeNode>>) -> Vec<i32> {
let mut queue = vec![];
let mut res = vec![];
if root.is_none() {
return res;
}
queue.push(root);
while !queue.is_empty() {
if let Some(node) = queue.remove(0) {
res.push(node.val);
if node.left.is_some() {
queue.push(node.left);
}
if node.right.is_some() {
queue.push(node.right);
}
}
}
res
}
}
#rust#


查看6道真题和解析