day 12-13 算法:二叉树最大最小深度,生成有效括号组合

本文深入探讨了二叉树的最大深度与最小深度的计算方法,采用深度优先搜索与广度优先搜索策略,同时讲解了如何通过回溯法生成有效的括号组合。文章提供了详细的算法实现代码,帮助读者理解并掌握这些核心算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 题目

  1. 二叉树的最大深度:给定一个二叉树,找出其最大深度(离根节点最远的路径节点个数)
  2. 二叉树的最小深度:给定一个二叉树,找出其最小深度(离根节点最近的路径节点个数)
  3. 生成有效的括号组合:给定数字n,写出一个函数,把所有闭合的括号组合输出,n代表生成括号的对数。

2. 算法题解题

2.1 二叉树的最大深度:给定一个二叉树,找出其最大深度(离根节点最远的路径节点个数)

解法1:深度优先DFS,递归
分别将左右子树的最大深度算出来再加1即当前二叉树的最大深度。
时间复杂度O(n),空间复杂度O(1)

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

        return max;
    }
}

2.2 二叉树的最小深度:给定一个二叉树,找出其最小深度(离根节点最近的路径节点个数)

解法1:深度优先DFS,递归
分别将左右子树的最小深度算出来再加1即当前二叉树的最小深度。
时间复杂度O(n),空间复杂度O(1)

public int minDepth (TreeNode root){
    if (root == null)
        return 0;
    if (root.left== null && root.right == null)
        return 1;

    int minDepth = Integer.MIN_VALUE;
    if (root.left != null)
        minDepth = Math.min(minDepth(root.left), minDepth);

    if (root.right != null)
        minDepth = Math.min(minDepth(root.right), minDepth);

    return minDepth + 1;
}

解法2: 广度优先搜索,迭代
使用队列辅助,按顺序取出TreeNode,只要第一个节点是叶子节点,那么就返回当前节点的深度即可。

public int minDepth(TreeNode root){

    LinkedList<Pair<TreeNode, Integer>> pairs = new LinkedList<>();

    if (root == null)
        return 0;
    //将根节点放入队列
    pairs.add(new Pair<TreeNode, Integer>(root, 1));

    int minDepth = 0;
    while (!pairs.isEmpty()){
        // 先进先出
        Pair<TreeNode, Integer> pair = pairs.poll();
        TreeNode node = pair.first;
        minDepth = pair.second;

        if (node.left == null && node.right == null)
            break;

        if (node.left != null)
            pairs.add(new Pair<TreeNode, Integer>(node.left, minDepth +1));
        if (node.right != null)
            pairs.add(new Pair<TreeNode, Integer>(node.right, minDepth + 1));
    }
    return minDepth;
}

2.3 生成有效的括号组合:给定数字n,写出一个函数,把所有闭合的括号组合输出,n代表生成括号的对数

解法1: 回溯法
判断括号是否有效,再继续添加有效括号,直到左右括号匹配,并且字符串长度为2*n时,添加到集合中。再执行递归剩余的逻辑,不断穷举,这个问题比较抽象。
时间复杂度O(2n) 空间复杂度 O(n)
public static List generateParenthesis(int n){
List combinations = new ArrayList<>();

    addGenerateOneByOne(combinations, "", 0, 0 ,n);
    return combinations;
}

private static void addGenerateOneByOne(List<String> combinations, String s, int open, int close, int max) {
    
    if (s.length() == max *2)
        combinations.add(s);
    if (open < max)
        addGenerateOneByOne(combinations, s.concat("("), open +1, close, max);

    if (close < open)
        addGenerateOneByOne(combinations, s.concat(")"), open, close + 1, max);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值