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

   1         3     3      2      1    \//      /\           3     2     1      1   3      2    /     /       \                    2     1         2                 3

Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ ' s Binary Tree serialization:

The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.

Here's an example:

   1  /  2   3    /   4         5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". Test instructions: It is possible to find a two interpolation tree consisting of n number.

Idea: N number can be used as the node of the tree, so each layer is selected a node, and then combined left and right two sub-tree case.

/** * 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> Generate Trees (int n) {return Dfs (0, n-1);    } Private list<treenode> dfs (int beg, int end) {list<treenode> ans = new arraylist<treenode> (); if (beg ; End) {ans.add (null); return ans;} for (int i = beg; I <= end; i++) {list<treenode> left = Dfs (Beg, i-1); list<treenode> right = DFS (i+1, end), for (int j = 0; J < Left.size (), j + +) for (int k = 0; k < right.size (); +) {TreeNode tmp = new TreeNode (i+1); Ans.add (tmp); tmp.left = Left.get (j); tmp.right = Right.get (k);}} return ans;}}
   




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.