95. Unique Binary Search Trees II(js)
95. Unique Binary Search Trees II
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
题意:给定一个数字,求出所有组成的二叉搜索树
代码如下:
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {number} n * @return {TreeNode[]} */ var generateTrees = function(n) { if(n<1){ return []; } return backtrack(1,n); }; var backtrack=function(start,end){ var res=[]; if(start>end){ res.push(null); return res; } for(var i=start;i<=end;i++){ var leftNode=backtrack(start,i-1); var rightNode=backtrack(i+1,end); for(var l=0;l<leftNode.length;l++){ for(var r=0;r<rightNode.length;r++){ var root=new TreeNode(i); root.left=leftNode[l]; root.right=rightNode[r]; res.push(root); } } } return res; }