力扣算法 Java 刷题笔记【二叉搜索树 BST 篇】hot100(三)不同的二叉搜索树 2

1. 不同的二叉搜索树(中等)

二叉树算法的关键就在于明确根节点需要做什么,其实 BST 作为一种特殊的二叉树,核心思路也是一样的。
地址: https://leetcode-cn.com/problems/unique-binary-search-trees/
2021/12/04
做题反思:新建数组

class Solution {
    
    
    public int numTrees(int n) {
    
    
        memo = new int[n + 1][n + 1];
        return count(1, n);
    }

    int[][] memo;
    int count(int lo, int hi) {
    
    
        if (lo > hi) {
    
    
            return 1;
        }
        if (memo[lo][hi] != 0) {
    
    
            return memo[lo][hi];
        }
        int res = 0;
        for (int i = lo; i <= hi; i++) {
    
    
            int left = count(lo, i - 1);
            int right = count(i + 1, hi);
            res += left * right;
        }
        memo[lo][hi] = res;
        return res;
        
    }
}

在这里插入图片描述

2. 不同的二叉搜索树 II (中等)

地址: https://leetcode-cn.com/problems/unique-binary-search-trees-ii/
2021/12/02
做题反思:res的位置

class Solution {
    
    
    public List<TreeNode> generateTrees(int n) {
    
    
        if (n == 0) {
    
    
            return new LinkedList<>();
        }
        return build(1, n);
    }
    
    List<TreeNode> build(int lo, int hi) {
    
    
        List<TreeNode> res = new LinkedList<>();
        if (lo > hi) {
    
    
            res.add(null);
            return res;
        }
        for (int i = lo; i <= hi; i++) {
    
    
            List<TreeNode> leftTree = build(lo, i - 1);
            List<TreeNode> rightTree = build(i + 1, hi);
            for (TreeNode left : leftTree) {
    
    
                for (TreeNode right : rightTree) {
    
    
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    res.add(root);
                }
            }
        }

        return res;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46644403/article/details/121669790
今日推荐