题解 | #二叉树的深度#

二叉树的深度

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;
    }
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务