给定一个值n,请生成所有的存储值1...n.的二叉搜索树(BST)的结构java实现

给定一个值n,能构建出多少不同的值包含1...n的二叉搜索树(BST)https://blog.csdn.net/zy854816286/article/details/104820348

若要输出所有的二叉搜索树结构,则依次考虑以1为根节点,以2为根节点...直到以n为根节点。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; left = null; right = null; }
 * }
 */
import java.util.*;
public class Solution {
    public ArrayList generateTrees(int n) {
        return BST(1,n);
    }
    public ArrayList BST(int start,int end){
        ArrayList result=new ArrayList();
        if(start>end){
            result.add(null);
            return result;
        }
        int i,j;
        for(i=start;i<=end;i++){
            ArrayList left=BST(start,i-1);
            ArrayList right=BST(i+1,end);
            for(int m=0;m

 

你可能感兴趣的:(LeetCode)