Unique Binary Search Trees II

[leetcode]Unique Binary Search Trees II

链接:https://leetcode.com/problems/unique-binary-search-trees-ii/description/

Question

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

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
  vector generateTrees(int n) {
    if (n == 0) return vector();
    return generate(1, n);
  }

  // 分治算法生成
  vector generate(int s, int e) {
    std::vector res;
    if (s > e) {
      res.push_back(NULL);
      return res;
    }
    for (int i = s; i <= e; i++) {
      // 得到左边的所有可能子树
      std::vector leftTrees = generate(s, i-1);
      std::vector rightTrees = generate(i+1, e);
      for (int j = 0; j < leftTrees.size(); j++) {
        for (int k = 0; k < rightTrees.size(); k++) {
          TreeNode* newroot = new TreeNode(i);
          newroot->left = leftTrees[j];
          newroot->right = rightTrees[k];
          res.push_back(newroot);
        }
      }
    }
    return res;
  }
};

思路:采用分治算法,遍历所有可能的根节点,然后分治为左边一棵BST,右边一棵BST。

你可能感兴趣的:(leetcode,分治)