Unique Binary Search Trees II

11 篇文章 0 订阅
1 篇文章 0 订阅

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

Idea: Each time we choose a key, in the range of [i,j] as the root. Then call generator(i,k-10) and generator(k+1, j) to get the all the possible left subtrees LEFT, and right subtrees RIGHT. Then we just list all the combination (leftsubtree, rightsubtree), and add the root to the result list RST.

VERSION 1 [WONG]

public class Solution {
	public List<TreeNode> generateTrees(int n) {
		return generator(1, n);
	}
	private List<TreeNode> generator(int l, int h) {
		ArrayList<TreeNode> rst = new ArrayList<>();

		if (l > h) {
			rst.add(null);
		} else if (l == h) {
			rst.add(new TreeNode(l));
		} else {
			for (int k = l; k <= h; k++) {
				<span style="color:#FF0000;">TreeNode root = new TreeNode(k);</span>
				List<TreeNode> left = generator(l, k - 1);
				List<TreeNode> right = generator(k + 1, h);
				for(TreeNode ln : left){
					for(TreeNode rn : right){
						root.left = ln;
						root.right = rn;
						rst.add(root);
					}
				}
			}
		}
		return rst;
	}
}

Input:3

Output:[{1,#,3,2},{1,#,3,2},{2,1,3},{3,2,#,1},{3,2,#,1}]

Expected:[{1,#,2,#,3},{1,#,3,2},{2,1,3},{3,1,#,#,2},{3,2,#,1}] 

REASON: if we create the root node outside the two for loops: 

				for(TreeNode ln : left){
					for(TreeNode rn : right){

we only create one node for all the conbination for that node! OBJECT is add to rst BY REFERENCE. 


VERSION2 [CORRECT]:

public class UniqueBinarySearchTreesII {
	public List<TreeNode> generateTrees(int n) {
		return generator(1, n);
	}
	private List<TreeNode> generator(int l, int h) {
		ArrayList<TreeNode> rst = new ArrayList<>();

		if (l > h) {
			rst.add(null);
		} else if (l == h) {
			rst.add(new TreeNode(l));
		} else {
			for (int k = l; k <= h; k++) {
				List<TreeNode> left = generator(l, k - 1);
				List<TreeNode> right = generator(k + 1, h);
				for(TreeNode ln : left){
					for(TreeNode rn : right){
					<span style="color:#FF0000;">	TreeNode root = new TreeNode(k);</span>
						root.left = ln;
						root.right = rn;
						rst.add(root);
					}
				}
			}
		}
		return rst;
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值