Unique Binary Search Trees II Java

本文提供了一种使用递归循环方法生成从1到n的所有唯一二叉搜索树的方法,包括理解复杂参数如'{1,#,2,3}

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

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

confused what "{1,#,2,3}" means?

 This problem is belong to NP-Problem Category,
    And similar idea of N-Queues problem
    solve by Loop-Recursion method
    Idea:
    1. Recursion for nodes of leftList and rightList
        leftList=(left,i-1), rightList=(i+1,right)
    2. Use Nested Loop with depth 2
        set (i as root),
    3. connect left and right one by one
        nested Loop index j(leftList) and k(rightList)
    4. Finally, add root into result list

public class Solution {
    public List<TreeNode> generateTrees(int n) {
     return helper(1,n);
    }
    private ArrayList<TreeNode> helper(int left, int right){
        ArrayList<TreeNode> res=new ArrayList<TreeNode>();
        //base case
        if(left>right){
            res.add(null);
        }
        //recursion case
        for(int i=left;i<=right;i++) {
            ArrayList<TreeNode> leftList = helper(left, i - 1);
            ArrayList<TreeNode> rightList = helper(i+1,right);
            //gernate tree from leftList and rightList;
            for(int j=0;j<leftList.size();j++){
                for(int k=0;k<rightList.size();k++){
                    TreeNode root=new TreeNode(i);
                    root.left=leftList.get(j);
                    root.right=rightList.get(k);
                    res.add(root);
                }
            }
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值