剑指 Offer 55 - I. 二叉树的深度

在这里插入图片描述

递归

如果一棵二叉树没有左右子树那么深度为1;如果只有左子树那么深度为左子树深度加1;如果只有右子树那么深度为右子树深度加1;如果既有左子树,又有右子树那么深度为左右子树深度的最大者加1

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth)+1;
    }
}
posted @ 2020-09-19 09:55  消灭猕猴桃  阅读(38)  评论(0编辑  收藏  举报