博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Unique Binary Search Trees II dfs 深度搜索
阅读量:6901 次
发布时间:2019-06-27

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

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? 

 

Hide Tags
   
 

  这个嘛,对于1 to n ,如果要用某个值做节点,那么这个值左部分的全部可能的树,递归调用获得,右部分同理,这样便可以获取结果。
 
#include 
#include
using namespace std;/** * 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
generateTrees(int n) { return help_f(1,n); } vector
help_f(int l,int r) { vector
ret; if(l>r){ ret.push_back(NULL); return ret; } for(int i=l;i<=r;i++){ vector
lPart = help_f(l,i-1); vector
rPart = help_f(i+1,r); for(int lidx=0;lidx
left = lPart[lidx]; pNode->right = rPart[ridx]; ret.push_back(pNode); } } } return ret; }};int main(){ return 0;}

 

转载于:https://www.cnblogs.com/Azhu/p/4240413.html

你可能感兴趣的文章
我的友情链接
查看>>
UITabelView的分割线处理及介绍
查看>>
Spring整合MyBatis
查看>>
打印机拒绝访问无法连接
查看>>
Linux学习路线图
查看>>
Linux系统下常见性能分析工具的使用
查看>>
事件驱动模型
查看>>
ASP.NET MVC 音乐商店 - 3. 视图与模型
查看>>
mcollective安装文档
查看>>
GRE隧道模式与IPSec传输模式构建×××
查看>>
linux命令6--touch命令
查看>>
我的友情链接
查看>>
且谈布局适配和日志框架
查看>>
在论坛中出现的比较难的sql问题:15(行转列2)
查看>>
springboot中的5种通知小例子
查看>>
mysql数据通过jdbc操作作为Spark数据源案例
查看>>
Sersync实现触发式文件同步
查看>>
shell练习题
查看>>
大型网站压力测试及优化方案
查看>>
云计算的特性有这4点
查看>>