Java for Leetcode 095 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 should return all 5 unique BST ' s shown below.

Problem Solving Ideas:

Refer to Java for leetcode 096 Unique Binary Search trees ideas, the subject is easy to solve. Note that if you try to use an object's reference without copying it, you can't get the correct result, but you can also use DFS, but given the Java object-oriented features, we're using Java for Leetcode 096 Unique Binary Search Trees the idea of it.

The Java implementation is as follows:

static public list<treenode> generatetrees (int n) {list<treenode> List = new arraylist<treenode> (); (n = = 0) {list.add (null); return list;} if (n = = 1) {List.add (new TreeNode (1)); return list;} for (int k = 0, K <= n-1; k++) {list<treenode> left = Generatetrees (k);  List<treenode> right = Generatetrees (N-k-1), for (TreeNode rightnode:right) plus (Rightnode, k + 1); for (TreeNode Leftnode:left) {for (TreeNode rightnode:right) {TreeNode TN = new TreeNode (k + 1); Tn.left = Treenodeclone (Leftnode); Tn.right = Treenodeclone (Rightnode); List.add (TN);}}} return list;} public static void plus (TreeNode root, int num) {if (root = null) Return;root.val + = Num;plus (root.left, num);p LUs (Root.ri Ght, num);} public static TreeNode Treenodeclone (TreeNode TN1) {if (tn1==null) return null; TreeNode tn2=new TreeNode (tn1.val); Tn2.left=treenodeclone (Tn1.left); Tn2.right=treenodeclone (tn1.right); return TN2;}

Java for Leetcode 095 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.