题解 | #实现二叉树先序,中序和后序遍历# | Rust
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/**
* #[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类 the root of binary tree
* @return int整型二维数组
*/
pub fn threeOrders(&self, root: Option<Box<TreeNode>>) -> Vec<Vec<i32>> {
let mut ans : Vec<Vec<i32>> = vec![vec![],vec![],vec![]];
Solution::dfs(self, root, &mut ans);
return ans;
}
fn dfs(&self, node: Option<Box<TreeNode>>, ans:&mut Vec<Vec<i32>>) {
if let Some(mut node) = node {
ans[0].push(node.val);
Solution::dfs(self, node.left, ans);
ans[1].push(node.val);
Solution::dfs(self, node.right, ans);
ans[2].push(node.val);
}
}
}
查看18道真题和解析