leetcode试题之求二叉搜索树的个数

    xiaoxiao2021-12-15  29

    /** * * * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 * */ import java.util.*; public class UniqueBinaryTree{ public static void main(String args[]){ UniqueBinaryTree unique = new UniqueBinaryTree(); unique.numTrees(3); } public int numTrees(int n) { if(n == 0) { return 1; } if(n == 1) { return 1; } if(n ==2) { return 2; } int result =0; for(int i=1;i<=n;i++) { result += numTrees(i-1)*numTrees(n-i); } System.out.println("the final result is"+"----->"+result); return result; } }

    sh-3.2# java UniqueBinaryTree the final result is----->5

    转载请注明原文地址: https://ju.6miu.com/read-1000155.html

    最新回复(0)