BM28 二叉树的最大深度

19 篇文章 0 订阅

在这里插入图片描述
第一种:用集合来存储已经走的层数,最后返回集合的大小就是最大的层数,时间复杂度O(n),空间复杂度O(n)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if (root == null) {
            return 0;
        }
        Set<Integer> set = new HashSet<>();
        //depth = 1 表示从第一层开始遍历
        //set保存的就是层数
        getDepth(root, set, 1);
        return set.size();
    }

    private void getDepth(TreeNode root, Set<Integer> set, int depth) {
        if (root == null) {
            return ;
        }
        set.add(depth);
        getDepth(root.left, set, depth + 1);
        getDepth(root.right, set, depth + 1);
    }
}

第二种:用一个变量表示最大层数,时间复杂度O(n),空间复杂度O(1)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    private int max = 0;
    public int maxDepth (TreeNode root) {
        // write code here
        if (root == null) {
            return 0;
        }
        //depth = 1 表示从第一层开始遍历
        //max表示最大层数
        getDepth(root, 1);
        return max;
    }

    private void getDepth(TreeNode root, int depth) {
        if (root == null) {
            return ;
        }
        max = max > depth ? max : depth;
        getDepth(root.left, depth + 1);
        getDepth(root.right, depth + 1);
    }
}

第三种:递归求解,因为题目是求root的最高深度,也就是求max(root.left,root.right)的最大值+1,依次递归即可,时间复杂度O(n),空间复杂度O(1)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if (root == null) {
            return 0;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值