题解 | #二叉树的深度#

二叉树的深度

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

import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/



/**
解题思路:
只需要计算出左子树的最大深度或者右子树的最大深度即可

计算出来后,树的总高度就为max(左子树,右子树) + 1

问题的关键点就在于怎么计算一个树的高度:当一个树没有左右节点时,树的深度就是1

 */

public class Solution {
    public int TreeDepth(TreeNode root) {

        // 临界条件判断,同时也是递归出口,当一颗树的左/右节点为null,说明该树的左/右高度为0
        if(root == null){
            return 0;
        }
        // 计算左子树高度
        int leftL = 0;
        int rightL = 0;
        int max = 0;
        if(root.left != null){
            leftL = TreeDepth(root.left);
        }
        if(root.right != null){
            rightL = TreeDepth(root.right);
        }
        max = leftL > rightL ? leftL + 1 : rightL + 1;

        return max;
    }
}

全部评论

相关推荐

水墨不写bug:疑似没有上过大学
点赞 评论 收藏
分享
强大的马里奥:不太可能,我校计算机硕士就业率99%
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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