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

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

1、


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

分析:本题非常easy想到用递归的方法,依次将每一个点作为根结点,然后递归左右子树,可是在这个递归中有个问题,怎样推断递归结束,怎样保留上层的结点,怎样推断递归的是左子树还是有子树,递归的写法还是非常重要的。本题中,採用每次先求得下层子树左右子树的结点,然后依据左右子树的不同情况形成不同的树,保存这些树的根结点。

代码例如以下:

class Solution {public:    vector
generateTrees(int n) { return constructTree(0,n-1); } vector
constructTree(int startIndex, int endIndex){ vector
result; //保存下一层的结点 if(startIndex > endIndex){ result.push_back(NULL); return result; } for(int i=startIndex; i<=endIndex; ++i){ vector
leftTrees = constructTree(startIndex,i-1); vector
rightTrees = constructTree(i+1,endIndex); for(int j=0; j
left = leftTrees[j]; newNode->right = rightTrees[k]; } } } return result; }};

2、Unique Binary Search Trees 

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,

Given n = 3, there are a total of 5 unique BST's.

1         3     3      2      1    \       /     /      / \      \     3     2     1      1   3      2    /     /       \                 \   2     1         2                 3

分析:先做上面的题,后面这个题就简单了,採用递归,每次计算下层的左子树和右子树的数目,本层的不同树的个数为左子树的数目与右子树的数目相乘,每种不同的情况相加就可以。

class Solution {public:    int numTrees(int n) {        if(n < 1){            return 1;        }        return numTrees(1,n);    }    int numTrees(int startIndex, int endIndex){        int num = 1;        if(startIndex > endIndex){            return num;        }        num = 0;        for(int i=startIndex; i<=endIndex; ++i){            int leftNum = numTrees(startIndex,i-1);            int rightNum = numTrees(i+1,endIndex);            num += leftNum * rightNum;        }        return num;    }};

转载于:https://www.cnblogs.com/xfgnongmin/p/10615294.html

你可能感兴趣的文章
mysql workbench连接不上远程数据库,xshell无法连接远程主机的问题
查看>>
jquery 取id模糊查询
查看>>
解决在vue中,自用mask模态框出来后,下层的元素依旧可以滑动的问题
查看>>
左偏树
查看>>
修改系统启动项 grub2配置的方法 ubuntu[转]
查看>>
深入探索c++对象模型
查看>>
bc 函数库同意
查看>>
[转]Ubuntu中apt与apt-get命令的区别
查看>>
修改node节点名称
查看>>
Java 文件下载
查看>>
图论——读书笔记 (深度优先搜索)
查看>>
PAT(B) 1014 福尔摩斯的约会(Java)
查看>>
PAT甲级题解-1123. Is It a Complete AVL Tree (30)-AVL树+满二叉树
查看>>
不要过早追求通用
查看>>
带ifrmae的弹窗
查看>>
20172310 2017-2018《程序设计与数据结构》(下)第二周学习总结
查看>>
oj教程--坑
查看>>
C#中webBrowser加载页面中的不同域的iFrame的源代码的取得
查看>>
iOS/Android 微信及浏览器中唤起本地APP
查看>>
[Usaco2005 nov]Grazing on the Run 边跑边吃草 BZOJ1742
查看>>