Created
September 6, 2013 18:29
Unique Binary Search Trees II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; left = null; right = null; } | |
* } | |
*/ | |
public class Solution { | |
public ArrayList<TreeNode> generateTrees(int n) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
ArrayList<TreeNode> result=generateBST(1,n); | |
return result; | |
} | |
public ArrayList<TreeNode> generateBST(int start, int end){ | |
ArrayList<TreeNode> subTree=new ArrayList<TreeNode>(); | |
if (start>end){ | |
subTree.add(null); | |
} | |
else if (start==end){ | |
subTree.add(new TreeNode(start)); | |
} | |
else{ | |
for (int i=start; i<=end; i++){ | |
// divied and conquer. | |
// get collection of all left trees and right trees | |
// then construct them together | |
ArrayList<TreeNode> leftTree=generateBST(start, i-1); | |
ArrayList<TreeNode> rightTree=generateBST(i+1, end); | |
for (TreeNode leftNode:leftTree){ | |
for(TreeNode rightNode:rightTree){ | |
TreeNode root=new TreeNode(i); | |
root.left=leftNode; | |
root.right=rightNode; | |
subTree.add(root); | |
} | |
} | |
} | |
} | |
return subTree; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment