[Leetcode] [JavaScript] Unique Binary Search Trees II

Source: Internet
Author: User

Unique Binary Search Trees II

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
https://leetcode.com/problems/unique-binary-search-trees-ii/#

Generates a two-fork sort tree of N nodes.

Follow the same idea, divide and conquer, from 1 to n traversal, select the current point for the root, smaller than the root in the left subtree, larger than the root in the right sub-tree.

Http://www.cnblogs.com/Liok3187/p/4948510.html

1 /**2 * Definition for a binary tree node.3 * Function TreeNode (val) {4 * This.val = val;5 * This.left = This.right = null;6  * }7  */8 /**9 * @param {number} nTen * @return {treenode[]} One  */ A varGeneratetrees =function(n) { -     returnGettree (1, n); -  the     functionGettree (start, end) { -         varRET =[], I, J, K, left, right, node; -         if(Start >end) { -             return[NULL]; +}Else if(Start = = =end) { -             return[NewTreeNode (start)]; +         } A          for(i = start; I <= end; i++){ atleft = Gettree (Start, i-1); -right = Gettree (i + 1, end); -              for(j = 0; J < Left.length; J + +){ -                  for(k = 0; k < right.length; k++){ -node =NewTreeNode (i); -Node.left =Left[j]; inNode.right =Right[k]; - Ret.push (node); to                 } +             } -         } the         returnret; *     } $};

[Leetcode] [JavaScript] Unique Binary Search Trees II

Related Article

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.