标签:style class blog code http tar
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
Analysis: 这道题是想的比较难,想通了的话,就好做了。我查看了网上的资料,发现别人的想法实在是太精秒了。http://blog.csdn.net/linhuanmars/article/details/24761459
这道题要求可行的二叉查找树的数量,其实二叉查找树可以任意取根,只要满足中序遍历有序的要求就可以。从处理子问题的角度来看,选取一个结点为根,就把结点切成左右子树,以这个结点为根的可行二叉树数量就是左右子树可行二叉树数量的乘积,所以总的数量是将以所有结点为根的可行结果累加起来。写成表达式如下:
1 public class Solution { 2 public int numTrees(int n) { 3 int result = 0; 4 if (n == 0 || n == 1) return 1; 5 if (n < 0) return 0; 6 for (int i = 0; i <= n - 1; i++) { 7 result += numTrees(i) * numTrees(n-i-1); 8 } 9 return result; 10 } 11 }
Leetcode: Unique Binary Search Trees,布布扣,bubuko.com
Leetcode: Unique Binary Search Trees
标签:style class blog code http tar
原文地址:http://www.cnblogs.com/EdwardLiu/p/3809815.html