Leetcode -- Unique Binary Search Trees II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.