题解 | #二叉树的直径# | Rust

二叉树的直径

https://www.nowcoder.com/practice/15f977cedc5a4ffa8f03a3433d18650d

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

    fn dfs(&self, node: Option<Box<TreeNode>>, ans: &mut i32) -> i32 {
        if node.is_none() {
            return 0;
        }
        let mut node = node;
        let l = Solution::dfs(self, node.as_mut().unwrap().left.take(), ans);
        let r = Solution::dfs(self, node.as_mut().unwrap().right.take(), ans);
        *ans = std::cmp::max(*ans, l+r);
        return 1 + std::cmp::max(l, r);
    }
}

全部评论

相关推荐

04-15 23:42
中山大学 Java
ResourceUtilization:过几天楼主就会捧着一堆offer来问牛友们该怎么选辣
点赞 评论 收藏
分享
05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务