题目描述

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

牛客网刷题地址

思路分析

  利用递归,先计算左右子树的深度,判断左子树和右子树深度,大的+1 即为此二叉树的深度。

测试用例

  1. 功能测试:输入普通的二叉树;二叉树中所有节点都没有左/右子树。
  2. 特殊输入测试:二叉树只有一个节点;二叉树的头节点为nullptr指针。

Java代码

public class Offer055_01 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

    public static int TreeDepth(TreeNode root) {
        return Solution1(root);
    }

    private static int Solution1(TreeNode root) {
        if(root==null) {
            return 0;
        }
        int leftDep = Solution1(root.left);
        int rightDep = Solution1(root.right);
        
        return (leftDep>rightDep)? (leftDep+1):(rightDep+1);
    }

    private static void test1() {

    }

    private static void test2() {

    }
    private static void test3() {

    }

}

代码链接

剑指Offer代码-Java

相关文章:

  • 2021-09-29
  • 2021-09-17
  • 2021-06-04
  • 2022-01-09
  • 2022-12-23
  • 2021-11-26
猜你喜欢
  • 2021-12-12
  • 2022-02-05
  • 2021-07-16
  • 2021-09-07
  • 2022-12-23
  • 2022-02-14
相关资源
相似解决方案