题解 | #二叉树的深度#rust

二叉树的深度

https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b

/**
 * #[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 pRoot TreeNode类 
        * @return int整型
    */
    pub fn TreeDepth(&self, pRoot: Option<Box<TreeNode>>) -> i32 {
        // write code here
        // 空间复杂度O(n) 时间复杂度O(n)
        if pRoot.is_none() {
            return 0;
            }
        let mut left_height = 0;
        let mut right_height = 0;
        if let Some(root) = pRoot{
		  // Box类型,有自动deref功能,所以可以直接写root.left,不需要*root.left
            left_height = self.TreeDepth(root.left)+1;
            right_height = self.TreeDepth(root.right)+1;
            
        }
        if left_height > right_height {
            left_height
        } else {
            right_height
        }
    }
}

#rust#
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
点赞 评论 收藏
分享
07-01 17:14
中北大学 Java
兄弟们是真是假
牛客46374834...:我在boss上投java岗从来没成功过
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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