【leetcode】95. Unique Binary Search Trees II 含有N个节点的中序遍历有序的二叉树集

1. 题目

Given an integer 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

2. 思路

递归的方式处理,对于N各节点的二叉树,分别对应的就是左边i个,右边N-i-1个,根节点一个。i的取值范围是0到N-1. 初始为0个的场景即可。这里为了降低一次递归,把一个的场景也放在初始值里。

3. 代码

/**
 * 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<TreeNode*> generateTrees(int n) {
        if (n == 0) {
            vector<TreeNode*> ret;
            return ret;
        }
        return generateTrees(n, 1);
    }
    vector<TreeNode*> generateTrees(int n, int val_start) {
        vector<TreeNode*> ret;
        if (n == 0) { 
            ret.push_back(NULL);
            return ret;
        }
        if (n == 1) {
            ret.push_back(new TreeNode(val_start));
            return ret;
        }
        
        for (int i = 0; i < n; i++) {
            vector<TreeNode*> left = generateTrees(i, val_start);
            vector<TreeNode*> right = generateTrees(n-1-i, val_start+i+1);
            for (int l = 0; l < left.size(); l++) {
                for (int r = 0; r < right.size(); r++) {
                    TreeNode* root = new TreeNode(val_start+i);
                    root->left = left[l];
                    root->right = right[r];
                    ret.push_back(root);
                }
            }
        }
        
        return ret;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007443961
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞