LeetCode *** 95. Unique Binary Search Trees II

来源:互联网 发布:js改变全局变量的值 编辑:程序博客网 时间:2024/05/17 06:16

题目:

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}".


分析:

无。


代码:

/** * 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)return vector<TreeNode*>{};        return generateTrees(1,n);    }        vector<TreeNode*> generateTrees(int s,int e){                vector<TreeNode*> res;        if(s>e){            res.push_back(NULL);            return res;        }                for(int i=s;i<=e;++i){                        vector<TreeNode*> l=generateTrees(s,i-1);            vector<TreeNode*> r=generateTrees(i+1,e);                        for(TreeNode* left:l)                for(TreeNode* right:r){                    TreeNode* root=new TreeNode(i);                    root->left=left;                    root->right=right;                    res.push_back(root);                }        }        return res;            }};

0 0
原创粉丝点击