程序员人生 网站导航

生成所有的BST

栏目:php教程时间:2015-05-11 09:01:14

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

分析:对n,合法的BST有C(n,2*n)/(n+1))种.

依照后序建树,[1,..i⑴] i [i+1,..n]先分别建好左右合法的BST,然后接到root上。

设左子树形态有m种,右子树有k种,那末要尝试m*k种拼接方式。

public List<TreeNode> generateTrees(int l, int r) { List<TreeNode> list = new ArrayList<TreeNode>(); if (l > r) { list.add(null); return list; } for (int i = l; i <= r; i++) { List<TreeNode> lefts = generateTrees(l, i - 1); List<TreeNode> rights = generateTrees(i + 1, r); for (TreeNode left : lefts) { for (TreeNode right : rights) { TreeNode root = new TreeNode(i); root.left = left; root.right = right; list.add(root); } } } return list; } public List<TreeNode> generateTrees(int n) { return generateTrees(1, n); }


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐