Given N, generate all structurally unique BST's (Binary Search Trees) that store values 1... n.
For example,
Given n = 3, your program shocould return all 5 unique BST's shown below.
1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
Original question link: https://oj.leetcode.com/problems/unique-binary-search-trees-ii/
Idea: the same idea as the previous question about how to calculate the number of binary search trees, it is only necessary to build a tree here. Because the binary search tree is such a tree, the left node is smaller than the root node, and the root is smaller than the right node. Therefore, if you select node I as the root node, the (1, I) number can be used as the node of the Left subtree, and the (I + 1, n) number can be used as the node of the right subtree. Therefore, as long as all I is traversed, all trees can be obtained.
public List<TreeNode> generateTrees(int n) {return generateTrees(1,n);}public List<TreeNode> generateTrees(int start,int end) {List<TreeNode> list = new ArrayList<TreeNode>();if(start>end){list.add(null);return list;}for(int i=start;i<=end;i++){List<TreeNode> lefts = generateTrees(start,i-1);List<TreeNode> rights = generateTrees(i+1,end);for(TreeNode left : lefts){for(TreeNode right : rights){TreeNode node = new TreeNode(i);node.left = left;node.right = right;list.add(node);}}}return list;}// Definition for binary treepublic class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}}
Leetcode -- Unique Binary Search Trees II