Description:
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
和第I题的区别是这题要返回所有的结果,不是结果的数目。所以要递归枚举:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public Listgenerate(int start, int end) { List ret = new ArrayList (); if(start > end) { ret.add(null); return ret; } for(int i=start; i<=end; i++) { List lTree = generate(start, i-1); //生成左子树集合 List rTree = generate(i+1, end); //生成右子树集合 for(int j=0; j generateTrees(int n) { if(n <= 0) return new ArrayList (); return generate(0, n-1); }}
C++:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vectorgenerate(int start, int end) { vector ret; if (start > end) { ret.push_back(NULL); return ret; } for(int i = start; i <= end; i++) { vector lTree = generate(start, i - 1); vector rTree = generate(i + 1, end); for(int j = 0; j < lTree.size(); j++) for(int k = 0; k < rTree.size(); k++) { TreeNode *node = new TreeNode(i + 1); ret.push_back(node); node->left = lTree[j]; node->right = rTree[k]; } } return ret; } vector generateTrees(int n) { vector ret; if(n <= 0) return ret; return generate(0, n - 1); }};
同样的代码同样的测试数据Java代码为什么效率高这么多,难道是跑代码的服务器不一样?还是Java后台调用代码写的好?