博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Unique Binary Search Trees II
阅读量:5219 次
发布时间:2019-06-14

本文共 2189 字,大约阅读时间需要 7 分钟。

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  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     vector
generateTrees(int n) {13 // Start typing your C/C++ solution below14 // DO NOT write int main() function15 return generateTrees(1, n);16 }17 18 vector
generateTrees(int start, int end) 19 {20 // If the range is invalid, then return an empty tree21 vector
result;22 23 if (start > end) 24 {25 result.push_back(NULL);26 return result;27 }28 29 30 for (int i = start; i <= end; ++i) {31 // Generate all possible left subtrees (including the empty subtree)32 vector
leftSubtrees = generateTrees(start, i - 1);33 34 // Generate all possible right subtrees (including the empty subtree)35 vector
rightSubtrees = generateTrees(i + 1, end);36 37 // For each left subtree and each right subtree, create a root node38 // with value i and then link the two subtrees to the root39 for (int j = 0; j < leftSubtrees.size(); ++j) {40 for (int k = 0; k < rightSubtrees.size(); ++k) {41 TreeNode *root = new TreeNode(i);42 root->left = leftSubtrees[j];43 root->right = rightSubtrees[k];44 result.push_back(root);45 }46 }47 }48 return result;49 }50 51 };

 

转载于:https://www.cnblogs.com/caijinlong/archive/2013/05/01/3053605.html

你可能感兴趣的文章
phplib系统开发经验总结
查看>>
黄金点游戏
查看>>
bzoj 2054: 疯狂的馒头
查看>>
打卡帖
查看>>
“教室派”使用体验
查看>>
【机器学习】分类算法——Logistic回归
查看>>
htm 中 <b>和<strong>的区别
查看>>
中文词向量论文综述(二)
查看>>
[SHOI2008]小约翰的游戏
查看>>
# linux文件系统(inode block superblock)
查看>>
Add Two Numbers
查看>>
操作系统概论四
查看>>
POJ 1150 The Last Non-zero Digit
查看>>
html
查看>>
移动端物理/css/位图像素概念以及rem布局的实现
查看>>
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
查看>>
Django 分页器
查看>>
strcpy 一题
查看>>
对于有志于成为架构师的开发者,支付宝架构团队有何建议?
查看>>
C#多播委托详解
查看>>