【牛客-剑指offer-数据结构篇】JZ55 二叉树的深度 Java实现


1 题目链接

https://www.nowcoder.com/exam/oj/ta?page=1&tpId=13&type=13

2 题目

在这里插入图片描述
在这里插入图片描述

3 思路 & 答案

原问题:求二叉树的深度

将原问题拆解,原问题 = Max(根节点的左子树的深度,根节点的右子树的深度) + 1

不断地将问题进行拆解,直到叶子节点成为问题的根节点,返回1即可。

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

上面这个代码,在遇到叶子节点时还会继续调用TreeDepth方法,然后,叶子结点的左孩子和右孩子都为空,最后得到,叶子节点的深度为1。可以在上面的代码上再加上一个if判断语句,判断如果是叶子节点,直接返回1,省去判断其左孩子和右孩子是否为空。

public class Solution {
    public int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
    }
}

4 测试程序 & 运行结果

下面这个测试程序可以更直观的感受递归执行的过程

import org.junit.Test;

import java.util.*;

public class Solution {

    @Test
    public void test() {
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        TreeNode t4 = new TreeNode(4);
        TreeNode t5 = new TreeNode(5);
        TreeNode t6 = new TreeNode(6);
        TreeNode t7 = new TreeNode(7);

        t1.left = t2;
        t1.right = t3;
        t2.left = t4;
        t2.right = t5;
        t5.left = t7;
        t3.right = t6;


        int depth = TreeDepth(t1);
        System.out.println("这棵树的深度是:" + depth);
    }

    public int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int res = Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;

        System.out.println("当前节点 " + root.val + ":" + res);

        return res;
    }
}

运行结果

当前节点 4:1
当前节点 7:1
当前节点 5:2
当前节点 2:3
当前节点 6:1
当前节点 3:2
当前节点 1:4
这棵树的深度是:4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值