LeetCode19|二叉树的深度

时间:2022-07-23
本文章向大家介绍LeetCode19|二叉树的深度,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

输入一棵二叉树的根节点,求该树的深度。

从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

2,示例

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

    3
   / 
  9  20
    /  
   15   7
返回它的最大深度 3 

3,题解思路

递归的使用,求左右子树的最大高度

4,题解程序

public class MaxDepthTest {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(3);
        TreeNode t2 = new TreeNode(9);
        TreeNode t3 = new TreeNode(20);
        TreeNode t4 = new TreeNode(15);
        TreeNode t5 = new TreeNode(7);
        t1.left = t2;
        t1.right = t3;
        t3.left = t4;
        t4.right = t5;
        int maxDepth = maxDepth(t1);
        System.out.println("maxDepth = " + maxDepth);

    }

    public static int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}