LeetCode 95. Unique Binary Search Trees II 不同的二叉搜索树II(Java)

题目:

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.
在这里插入图片描述

解答:

本题没有想到解题思路,所以采用了官方给的解法,通过递归实现,值得好好学习。

首先二叉搜索树的特点是:左子树 < 根节点 < 右子树
所以要找到 1-n 所有的二叉搜索树,也就是找到以 1-n 中每个数为根节点时,其左子树及右子树可能的组成情况
若根节点的值为 i,则其左子树可能的节点为 [1, i),其右子树可能的节点为 (i, n]

所以采用递归的方法,通过树结构的层层递归,将问题转换为两个子问题:

  1. 找到左子树的所有可能组成
  2. 找到右子树的所有可能组成

具体递归部分的思路为:

  1. 层层遍历根节点 i 取值从 start 到 end,start 和 end 分别表示当前节点的左子树和右子树的取值范围,当前节点取值为 i 时,左子树 leftTree 取值必须 < 根节点,即为(start, i-1),右子树 rightTree 取值范围必须 > 根节点,即为(i+1, end)
  2. 得到左右子树后,分别遍历左右子树,并将节点的值写入 res
class Solution {
    public List<TreeNode> generateTrees(int n) {        
        if(n <= 0) {
            return new ArrayList<>();
        }
        return recursive(1, n);
    }
    private List<TreeNode> recursive(int start, int end) {
        List<TreeNode> res = new ArrayList<>();
        if(start > end) {
            res.add(null);
            return res;
        }
        for(int i=start; i<=end; i++) {
            List<TreeNode> leftTree = recursive(start, i-1);
            List<TreeNode> rightTree = recursive(i+1, end);
            for(TreeNode left : leftTree) {
                for(TreeNode right: rightTree) {
                    TreeNode node = new TreeNode(i);
                    node.left = left;
                    node.right = right;
                    res.add(node);
                }
            }
        }
        return res;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值