标签:
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
代码如下:
public List<TreeNode> generateTrees(int n) { if(n < 1) { List<TreeNode> list = new ArrayList<TreeNode>(); list.add(null); return list; } return generateTree(1, n); } public List<TreeNode> generateTree(int start ,int over) { List<TreeNode> list = new ArrayList<TreeNode>(); if(start > over) { list.add(null); return list; } if(start == over) { list.add(new TreeNode(start)); return list; } for(int i=start; i<=over; i++) { List<TreeNode> leftList = generateTree(start ,i-1); List<TreeNode> rightList = generateTree(i+1 ,over); for(TreeNode left : leftList) { for(TreeNode right : rightList) { TreeNode root = new TreeNode(i); root.left = left; root.right = right; list.add(root); } } } return list; }
LeetCode-95 Unique Binary Search Trees II
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4331143.html