题解 | #二叉树的中序遍历# | Rust

二叉树的中序遍历

https://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d

/**
 * #[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 inorderTraversal(&self, root: Option<Box<TreeNode>>) -> Vec<i32> {
        let mut ans : Vec<i32> = Vec::new();
        Solution::dfs(self, root.clone(), &mut ans);
        return ans;
    }

    fn dfs(&self, node: Option<Box<TreeNode>>, array: &mut Vec<i32>) {
        if node.is_none() == false {
            Solution::dfs(self, node.as_ref().unwrap().left.clone(), array);
            array.push(node.as_ref().unwrap().val);
            Solution::dfs(self, node.as_ref().unwrap().right.clone(), array);
        }
    }
}

全部评论

相关推荐

现在才开始投还有可能吗😭😭😭
牛客621925249号:开秋招了已经
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务