leetcode--Unique Binary Search Trees II
2015-06-11 10:47
465 查看
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.
题意:给定n,要求解出所有的排序二叉树,并且返回结果。
分类:二叉树
解法1:个人认为这个题目不好做。关键在于递归思想的领悟。大家可以先参考Unique Binary Search Trees的思路。
假设我们有一个函数helper(int start,int end)可以返回从start到end的所有排序二叉树。
那么我们要求的就是helper(1,n)
同样,从1到n,我们逐个选定为根节点
对于选定的i,则helper(1,i-1)可以算出左边可以组成多少排序二叉树,helper(i+1,n)可以算出右边组成多少排序二叉树
然后左边跟右边相互组合(如果求数目的话,只要相乘就可以了,可是题目求的是真正的树)
就可以得到以i为根节点的所有排序二叉树
以此类推,从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
题意:给定n,要求解出所有的排序二叉树,并且返回结果。
分类:二叉树
解法1:个人认为这个题目不好做。关键在于递归思想的领悟。大家可以先参考Unique Binary Search Trees的思路。
假设我们有一个函数helper(int start,int end)可以返回从start到end的所有排序二叉树。
那么我们要求的就是helper(1,n)
同样,从1到n,我们逐个选定为根节点
对于选定的i,则helper(1,i-1)可以算出左边可以组成多少排序二叉树,helper(i+1,n)可以算出右边组成多少排序二叉树
然后左边跟右边相互组合(如果求数目的话,只要相乘就可以了,可是题目求的是真正的树)
就可以得到以i为根节点的所有排序二叉树
以此类推,从1到n,逐个为根节点,最后组合成结果
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<TreeNode> generateTrees(int n) { return helper(1, n); } public List<TreeNode> helper(int start,int end){ List<TreeNode> res = new ArrayList<TreeNode>(); if(start>end){//如果end<start,说明结束 res.add(null); return res; } for(int i=start;i<=end;i++){//从start到end,逐个设置为根节点 List<TreeNode> left = helper(start, i-1);//递归求出所有的左子树 List<TreeNode> right = helper(i+1, end);//递归求出所有的右子树 for(TreeNode l:left){//左右子树相互组合 for(TreeNode r:right){ TreeNode t = new TreeNode(i);//生成根节点 t.left = l;//设置左子树 t.right = r;//设置右子树 res.add(t);//加入结果之中 } } } return res; } }
相关文章推荐
- A quick message queue benchmark: ActiveMQ, RabbitMQ, HornetQ, QPID, Apollo
- java 并发编程 AbstractQueuedSynchronizer 加锁和解锁分析
- UITableView的简单介绍和功能
- Null value was assigned to a property of primitive type setter of"原因及解决方
- powerbuilder开发的程序,查询功能中,listview中的属性列重复出现
- 为jenkins的每个build设置description
- Android含文档server结束(client UI接口异步请求的一部分)三
- 【EasyUI学习-2】Easyui Tree的异步加载
- 报错:ImportError: No module named 'requests'
- MUI实战开发第四集--如何增加自定义icon图标
- 关于使用unigui、webxone、mysql的几个问题
- java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
- UIPanGestureRecognizer手势影响UISlider拖动的问题及解决办法
- java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
- MUI仿今日头条第三集--侧滑菜单制作
- java.sql.SQLException: Can not issue empty query.
- java.sql.SQLException: Can not issue empty query.
- 跳出手掌心--如何立即触发UIButton边界事件
- 帮学长的jfinal+easyui
- “XXX.Index”不扩展类“System.Web.UI.Page”,因此此处不允许的问题