問題:html
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.node
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
解決:數組
① 本題要求返回的是全部符合條件的二叉查找樹,而Unique Binary Search Trees要求的是符合條件的二叉查找樹的棵數。spa
http://codeganker.blogspot.com/2014/04/unique-binary-search-trees-ii-leetcode.html
這道題是求解全部可行的二叉查找樹,從Unique Binary Search Trees中咱們已經知道,可行的二叉查找樹的數量是相應的卡特蘭數,不是一個多項式時間的數量級,因此咱們要求解全部的樹,天然是不能多項式時間內完成的了。算法上仍是用求解NP問題的方法來求解。code
思路是每次一次選取一個結點爲根,而後遞歸求解左右子樹的全部結果,最後根據左右子樹的返回的全部子樹,依次選取而後接上(每一個左邊的子樹跟全部右邊的子樹匹配,而每一個右邊的子樹也要跟全部的左邊子樹匹配,總共有左右子樹數量的乘積種狀況),構造好以後做爲當前樹的結果返回。htm
這道題的解題依據依然是:
當數組爲 1,2,3,4,.. i,.. n時,基於如下原則的BST建樹具備惟一性:
以i爲根節點的樹,其左子樹由[1, i-1]構成, 其右子樹由[i+1, n]構成。 blog
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution { //4ms
public List<TreeNode> generateTrees(int n) {
if(n <= 0) return new ArrayList<TreeNode>();
return generateTrees(1,n);//1做爲根開始,到n做爲根結束
}
public List<TreeNode> generateTrees(int start,int end){
List<TreeNode> res = new ArrayList<>();
if(start > end){
res.add(null);//?
return res;
}
for (int i = start;i <= end ;i ++ ) {
List<TreeNode> lefts = generateTrees(start,i - 1);//以i做爲根節點,左子樹由[1,i-1]構成
List<TreeNode> rights = generateTrees(i + 1,end);////右子樹由[i+1, n]構成
for (int j = 0;j < lefts.size();j ++ ) {
for (int k = 0;k < rights.size() ;k ++ ) {
TreeNode root = new TreeNode(i);
root.left = lefts.get(j);
root.right = rights.get(k);
res.add(root);//存儲全部可能行
}
}
}
return res;
}
}遞歸
② 在discuss中看到的非遞歸方法。ip
class Solution {//2ms public List<TreeNode> generateTrees(int n) { List<TreeNode> res = new ArrayList<>(); if (n <= 0) { return res; } if (n == 1) { res.add(new TreeNode(1)); return res; } List<TreeNode> list = generateTrees(n - 1); for (TreeNode root : list) { TreeNode newNode = new TreeNode(n); newNode.left = root; res.add(newNode); traverse(root, n, res); } return res; } private void traverse(TreeNode root, int n, List<TreeNode> res) { TreeNode cur = root; while (cur != null) { TreeNode temp = cur.right; TreeNode newNode = new TreeNode(n); cur.right = newNode; newNode.left = temp; res.add(copy(root)); cur.right = newNode.left; cur = cur.right; } } private TreeNode copy(TreeNode root) { if (root == null) { return null; } TreeNode head = new TreeNode(root.val); head.left = copy(root.left); head.right = copy(root.right); return head; } }