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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ’s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:

   1
  / \
 2   3
    /
   4
    \
     5

The above binary tree is serialized as 
"{1,2,3,#,#,4,#,#,5}".

题目解析:

返回所有二叉搜索树的集合!

还是基于上一道题目的思想,依次选取1…..n个结点为根,然后递归遍历。但是由于要构造各种各样的树,因此要将返回的孩子跟结点集,一个一个的进行遍历

        for(int i = begin;i <= end;i++){
            vector<TreeNode *>leftTrees = GSubTrees(begin,i-1);
            vector<TreeNode *>rightTrees = GSubTrees(i+1,end);
            for(int j = 0;j < leftTrees.size();j++){
                for(int k = 0;k < rightTrees.size();k++){
                    TreeNode *T = new TreeNode(i);//每次都要创建一个,不能共用!
                    T->left = leftTrees[j];
                    T->right = rightTrees[k];
                    tmp.push_back(T);
                }
            }
        }

完整代码如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode *> generateTrees(int n) {

        return GSubTrees(1,n);
    }
    vector<TreeNode *> GSubTrees(int begin,int end){
        vector<TreeNode *> tmp;
        if(begin>end){
            tmp.push_back(NULL);
            return tmp;
        }
        for(int i = begin;i <= end;i++){
            vector<TreeNode *>leftTrees = GSubTrees(begin,i-1);
            vector<TreeNode *>rightTrees = GSubTrees(i+1,end);
            for(int j = 0;j < leftTrees.size();j++){
                for(int k = 0;k < rightTrees.size();k++){
                    TreeNode *T = new TreeNode(i);//每次都要创建一个,不能共用!
                    T->left = leftTrees[j];
                    T->right = rightTrees[k];
                    tmp.push_back(T);
                }
            }
        }
        return tmp;
    }
};

点赞