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.
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
Solution:
/** * 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 List<TreeNode> generateTrees(int n) { return generateTrees(1,n); } public List<TreeNode> generateTrees(int begin, int end) { List<TreeNode> solution = new ArrayList<TreeNode>(); if(begin>end) { solution.add(null); return solution; } for(int i=begin; i<=end; i++) { List<TreeNode> left = generateTrees(begin, i-1); List<TreeNode> right = generateTrees(i+1, end); for(TreeNode leftNode: left) { for (TreeNode rightNode: right) { TreeNode node = new TreeNode(i); node.left = leftNode; node.right = rightNode; solution.add(node); } } } return solution; } }
No comments :
Post a Comment