LeetCode每日一题:独一的二叉搜索树 1

问题描述

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

问题分析

求一共有多少种二叉搜索树,我们可以求一个节点的左右子树各有多少个,把他们相乘起来就是有多少种,用递归来做就行了。

代码实现

public int numTrees(int n) {
        if (n <= 1) return 1;
        int count = 0;
        for (int i = 1; i <= n; i++) {
            count = count + numTrees(i - 1) * numTrees(n - i);
        }
        return count;
    }

你可能感兴趣的:(LeetCode每日一题:独一的二叉搜索树 1)