leetcode之unique-binary-search-trees-ii(求出1-n数组可以组成的所有BST二叉树)
题目
Given n, generate all structurally unique BST’s (binary search trees) that store values 1…n.
For example,
Given n = 3, your program should return all 5 unique BST’s shown below.
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
题意
给定一个数字n,求常数1-n可以组成的BST二叉树有哪些,并输出出来。
解题思路
1、首先先明确1-n每个值都可以作为BST的根节点;
2、针对具体某个i,其分为左子树1到i-1 ,以及右子树i+1到n;
3、针对左右子树,分别做递归,并递归对左右子树再分别求递归的左右子树;
4、将对应某个i的左右子树对一一配对,所有的左子树一一配对所有的右子树,共有num(left)*num(right)个组合。