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
We can observe that the problem can be divided into subproblems. Assume current root node is i, then all elements on the left side of i will be in the left subtree of root, and all elements of the right side of i will be in the right subtree of root. And the number of trees for root i will be number of left trees times number of right trees.
C++ Code:
/* * func: unique_BST * goal: find the total number of BSTs by given n nodes * @param n: the number of nodes * return: total number */ int unique_BST(int n){ if(n <= 1){ return 1; } int total = 0; for(int i=1; i<=n; ++i){ total += unique_BST(i-1) * unique_BST(n-i); } return total; }
Python Code:
# func: find the total number of BSTs # @param n: input total number of nodes # @return: total number of trees def unique_BST(n): if n <= 1: return 1 else: result = [] result.append(1) result.append(1) for i in xrange(2, n+1): curr_result = 0 for root in xrange(i): curr_result += result[root] * result[i-root-1] result.append(curr_result) return result[-1]
No comments:
Post a Comment