首页 > 代码库 > LeetCode Unique Binary Search Trees II

LeetCode 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

 1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; left = null; right = null; } 8  * } 9  */10 public class Solution {11      public List<TreeNode> generateTrees(int n) {12          return create(1, n);13      }14 15      List<TreeNode> create(int start,int end) {16          List<TreeNode> results = new ArrayList<TreeNode>();17          if (start > end) {18              results.add(null);19              return results;20          }21 22          for (int k = start; k <= end; k++) {23              List<TreeNode> left = create(start, k - 1);24              List<TreeNode> right = create(k + 1, end);25              for (int i = 0; i < left.size(); i++) {26                  for (int j = 0; j < right.size(); j++) {27                      TreeNode root = new TreeNode(k);28                      root.left = left.get(i);29                      root.right = right.get(j);30                      results.add(root);31                  }32              }33          }34          return results;35      }36 }

 

LeetCode Unique Binary Search Trees II