关于leetcode:leetcode树之二叉树的深度

本文次要记录一下leetcode树之二叉树的深度

题目

输出一棵二叉树的根节点,求该树的深度。从根节点到叶节点顺次通过的节点(含根、叶节点)造成树的一条门路,最长门路的长度为树的深度。

例如:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

 

提醒:

    节点总数 <= 10000

留神:本题与主站 104 题雷同:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftDepth = maxDepth(root.left) ;
        int rightDepth = maxDepth(root.right) ;
        return leftDepth > rightDepth ? leftDepth + 1  : rightDepth + 1;
    }
}

小结

这里采纳递归的形式,递归计算maxDepth(root.left)及maxDepth(root.right),最初取它们的最大值+1。

doc

  • 二叉树的深度

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理