Rust每日一题(15)--数据结构--二叉树的前序遍历
给你二叉树的根节点root,返回它节点值的前序
遍历。
leetcode
思路比较简单,可以采用递归或队列的方式来解决 主要是熟悉Rust以下几部分内容:
Some
或者.map
来进行模式匹配,对里面的数据解包,有几层Option就采用几层Some
或.map
borrow
或borrow_mut
来获取对内部数据T的借用;node.borrow().right.clone()
采用clone()
的方式否则会转移所right的所有权// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None
}
}
}
use std::rc::Rc;
use std::cell::RefCell;
struct Solution{}
impl Solution {
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut res = vec![];
// Solution::recursive(root, &mut res);
Solution::iterate(root, &mut res);
res
}
fn recursive(root: Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>){
if let Some(x ) = root {
res.push(x.borrow().val);
//访问左子节点
Solution::recursive(x.borrow().left.clone(), res);
Solution::recursive(x.borrow().right.clone(), res);
}
}
fn iterate(mut root: Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
let mut heap = vec![];
//1.遍历完节点并入栈
while root.is_some() || !heap.is_empty() {
//访问所有左子树
while let Some(node) = root {
//invirant root shrink
res.push(node.borrow().val);
heap.push(node.clone());
root = node.borrow().left.clone();
}
root = heap.pop();
if let Some(node) = root {
root = node.borrow().right.clone();
}
}
}
}
fn main(){
let mut root = TreeNode::new(2);
let left_1 = None;
let left_2= TreeNode::new(1);
let mut right = TreeNode::new(3);
right.right = None;
right.left = Some(Rc::new(RefCell::new(left_2)));
root.left = left_1;
root.right = Some(Rc::new(RefCell::new(right)));
let res = Solution::preorder_traversal(Some(Rc::new(RefCell::new(root))));
println!("{:?}", res);
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!