mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-26 15:56:29 +08:00
42 lines
1.3 KiB
Rust
42 lines
1.3 KiB
Rust
|
/**
|
||
|
* File: binary_tree_bfs.rs
|
||
|
* Created Time: 2023-04-07
|
||
|
* Author: xBLACKICEx (xBLACKICE@outlook.com)
|
||
|
*/
|
||
|
|
||
|
use std::collections::VecDeque;
|
||
|
use std::{cell::RefCell, rc::Rc};
|
||
|
use tree_node::{vec_to_tree, TreeNode};
|
||
|
include!("../include/include.rs");
|
||
|
|
||
|
fn level_order(root: &Rc<RefCell<TreeNode>>) -> Vec<i32> {
|
||
|
// 初始化队列,加入根结点
|
||
|
let mut que = VecDeque::new();
|
||
|
que.push_back(Rc::clone(&root));
|
||
|
// 初始化一个列表,用于保存遍历序列
|
||
|
let mut vec = Vec::new();
|
||
|
|
||
|
while let Some(node) = que.pop_front() { // 队列出队
|
||
|
vec.push(node.borrow().val); // 保存结点值
|
||
|
if let Some(left) = node.borrow().left.as_ref() {
|
||
|
que.push_back(Rc::clone(left)); // 左子结点入队
|
||
|
}
|
||
|
if let Some(right) = node.borrow().right.as_ref() {
|
||
|
que.push_back(Rc::clone(right)); // 右子结点入队
|
||
|
};
|
||
|
}
|
||
|
vec
|
||
|
}
|
||
|
|
||
|
/* Driver Code */
|
||
|
fn main() {
|
||
|
/* 初始化二叉树 */
|
||
|
// 这里借助了一个从数组直接生成二叉树的函数
|
||
|
let root = vec_to_tree(op_vec![1, 2, 3, 4, 5, 6, 7]).unwrap();
|
||
|
println!("初始化二叉树\n");
|
||
|
print_util::print_tree(&root);
|
||
|
|
||
|
/* 层序遍历 */
|
||
|
let vec = level_order(&root);
|
||
|
print!("\n层序遍历的结点打印序列 = {:?}", vec);
|
||
|
}
|