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

二叉树的后序遍历

https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541

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

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

全部评论

相关推荐

程序员牛肉:这一眼假啊,基本上都是骗人的,不然就涉及到职位贪腐了,就像之前华为的OD事件,看你运气好不好了
点赞 评论 收藏
分享
牛客583549203号:腾讯还好,况且实习而已,实习生流动性很大,属于正常现象,记得和HR委婉解释
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务