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.

   1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
/ \
2 3
/
4
\
5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

96. Unique Binary Search Trees 的扩展,96题只要算出所有不同BST的个数,这道题让把那些二叉树都表示出来。

用递归来解,划分左右子树,递归构造。

1. 根节点可以任取min ~ max (例如min = 1, max = n),假如取定为i。
2. 则left subtree由min ~ i-1组成,假设可以有L种可能。right subtree由i+1 ~ max组成,假设有R种可能。生成所有可能的left/right subtree。
3 对于每个生成的left subtree/right subtree组合<T_left(p), T_right(q)>,p = 1...L,q = 1...R,添加上根节点i而组成一颗新树。

Python:

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None def __repr__(self):
if self:
serial = []
queue = [self] while queue:
cur = queue[0] if cur:
serial.append(cur.val)
queue.append(cur.left)
queue.append(cur.right)
else:
serial.append("#") queue = queue[1:] while serial[-1] == "#":
serial.pop() return repr(serial) else:
return None class Solution:
# @return a list of tree node
def generateTrees(self, n):
return self.generateTreesRecu(1, n) def generateTreesRecu(self, low, high):
result = []
if low > high:
result.append(None)
for i in xrange(low, high + 1):
left = self.generateTreesRecu(low, i - 1)
right = self.generateTreesRecu(i + 1, high)
for j in left:
for k in right:
cur = TreeNode(i)
cur.left = j
cur.right = k
result.append(cur)
return result

C++:

class Solution {
public:
vector<TreeNode *> generateTrees(int n) {
return genBST(1, n);
} vector<TreeNode *> genBST(int min, int max) {
vector<TreeNode *> ret;
if(min>max) {
ret.push_back(NULL);
return ret;
} for(int i=min; i<=max; i++) {
vector<TreeNode*> leftSubTree = genBST(min,i-1);
vector<TreeNode*> rightSubTree = genBST(i+1,max);
for(int j=0; j<leftSubTree.size(); j++) {
for(int k=0; k<rightSubTree.size(); k++) {
TreeNode *root = new TreeNode(i);
root->left = leftSubTree[j];
root->right = rightSubTree[k];
ret.push_back(root);
}
}
} return ret;
}
};

类似题目:

[LeetCode] 96. Unique Binary Search Trees 唯一二叉搜索树 

All LeetCode Questions List 题目汇总

[LeetCode] 95. Unique Binary Search Trees II 唯一二叉搜索树 II的更多相关文章

  1. LeetCode OJ:Unique Binary Search Trees(唯一二叉搜索树)

    Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For examp ...

  2. 【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】

    [096-Unique Binary Search Trees(唯一二叉搜索树)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given n, how many s ...

  3. Leetcode96.Unique Binary Search Trees不同的二叉搜索树

    给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 假设n个节点存在二叉排序树的 ...

  4. [LeetCode] 95. Unique Binary Search Trees II(给定一个数字n,返回所有二叉搜索树) ☆☆☆

    Unique Binary Search Trees II leetcode java [LeetCode]Unique Binary Search Trees II 异构二叉查找树II Unique ...

  5. [leetcode]95. Unique Binary Search Trees II给定节点形成不同BST的集合

    Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ...

  6. [LeetCode] 95. Unique Binary Search Trees II 独一无二的二叉搜索树之二

    Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ...

  7. leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法

    Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...

  8. leetcode 95 Unique Binary Search Trees II ----- java

    Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ...

  9. LeetCode OJ:Binary Search Tree Iterator(二叉搜索树迭代器)

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

随机推荐

  1. SpringBoot启动流程及其原理

    Spring Boot.Spring MVC 和 Spring 有什么区别? 分别描述各自的特征: Spring 框架就像一个家族,有众多衍生产品例如 boot.security.jpa等等:但他们的 ...

  2. 网站安全DDOS攻击及监测

    一. 监测 在类Unix系统中可以使用top查看系统资源.进程.内存占用等信息.查看网络状态可以使用netstat.nmap等工具.若要查看实时的网络流量,监控TCP/IP连接等,则可以使用iftop ...

  3. Markdown 设置字体大小颜色及背景色

    一.更改字体.大小.颜色 <font face="黑体">我是黑体字</font><font face="微软雅黑">我是微 ...

  4. LeetCode 740. Delete and Earn

    原题链接在这里:https://leetcode.com/problems/delete-and-earn/ 题目: Given an array nums of integers, you can ...

  5. c++ main函数

    vs 2015的运行环境 1.参数 int main(int argc, char* argv[]) 1)两个参数的类型是固定的,但参数名可以是符合命名规则的任何命名 2)argv[0]为执行文件的路 ...

  6. 【转载】Visual Studio Code 构建 C/C++ 开发环境

    https://www.cnblogs.com/XieSir/articles/8288051.html 1. 安装 MinGW Distro / MinGW / GNU GCC 中的任何一款,( W ...

  7. Thread线程框架学习

    原文:https://www.cnblogs.com/wangkeqin/p/9351299.html Thread线程框架 线程定义:线程可以理解为一个特立独行的函数.其存在的意义,就是并行,避免了 ...

  8. 01-复杂度2 Maximum Subsequence Sum (25 分)

    Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A continuous subsequence is defined to ...

  9. Go内置函数

    append go语言中的append函数作用是在切片变量的后面追加新的数据,然后返回新的切片变量 func append(slice []Type, elems ...Type) []type sl ...

  10. Detection of Glacier Calving Margins with Convolutional Neural Networks: A Case Study

    利用Unet结构对landsat数据进行冰川裂缝提取,结构如下:训练集很小只有123张152*240图片