leetcode--Unique Binary Search Trees II

本文介绍了一种使用递归方法生成所有可能的唯一二叉搜索树的方法。通过递归地选择每个节点作为根节点,并生成所有可能的左子树和右子树来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


题意:给定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,逐个为根节点,最后组合成结果


[java]  view plain  copy
  1. /** 
  2.  * Definition for a binary tree node. 
  3.  * public class TreeNode { 
  4.  *     int val; 
  5.  *     TreeNode left; 
  6.  *     TreeNode right; 
  7.  *     TreeNode(int x) { val = x; } 
  8.  * } 
  9.  */  
  10. public class Solution {  
  11.     public List<TreeNode> generateTrees(int n) {  
  12.         return helper(1, n);          
  13.     }  
  14.       
  15.     public List<TreeNode> helper(int start,int end){        
  16.         List<TreeNode> res = new ArrayList<TreeNode>();  
  17.         if(start>end){//如果end<start,说明结束  
  18.             res.add(null);  
  19.             return res;  
  20.         }  
  21.         for(int i=start;i<=end;i++){//从start到end,逐个设置为根节点  
  22.             List<TreeNode> left = helper(start, i-1);//递归求出所有的左子树  
  23.             List<TreeNode> right = helper(i+1, end);//递归求出所有的右子树  
  24.             for(TreeNode l:left){//左右子树相互组合  
  25.                 for(TreeNode r:right){  
  26.                     TreeNode t = new TreeNode(i);//生成根节点  
  27.                     t.left = l;//设置左子树  
  28.                     t.right = r;//设置右子树  
  29.                     res.add(t);//加入结果之中  
  30.                 }  
  31.             }  
  32.         }  
  33.         return res;  
  34.     }  
  35. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46454641

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值