zoukankan      html  css  js  c++  java
  • LeetCode OJ 95. 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
    

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    这道题目要求构建出存储1...n的所有平衡二叉树,并且这些树是相互独立的,如果有M棵树,那么每个节点都要被new M次。我的想法就是遍历1~n,构建出每一个数字作为根节点时它的左子树和右子树,然后根节点加所有左右子树的组合就是我们要构建的BST。很明显这是递归的思想,代码如下:

     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> list = new ArrayList();
    12     public List<TreeNode> generateTrees(int n) {
    13         if(n<=0) return list;
    14         list = trees(1, n);
    15         return list;
    16     }
    17     
    18     public List<TreeNode> trees(int n, int m){  //构建BST
    19         List<TreeNode> clist = new ArrayList();
    20         if(m<n){
    21             clist.add(null);
    22             return clist;
    23         }
    24         if(m==n){
    25             TreeNode node = new TreeNode(n);
    26             clist.add(node);
    27             return clist;
    28         }
    29         for(int i = n; i<=m; i++){
    30             List<TreeNode> llist = trees(n, i-1);//构建所有的左子树
    31             List<TreeNode> rlist = trees(i+1, m);//构建所有的右子树
    32             for(TreeNode lnode:llist){           //生成以i为根节点的所有BST
    33                 for(TreeNode rnode:rlist){
    34                     TreeNode root = new TreeNode(i);
    35                     root.left = copyTree(lnode);
    36                     root.right = copyTree(rnode);
    37                     clist.add(root);
    38                 }
    39             }
    40         }
    41         return clist;
    42     }
    43     
    44     public TreeNode copyTree(TreeNode root){    //复制二叉树
    45         if(root==null) return null;
    46         else{
    47             TreeNode croot = new TreeNode(root.val);
    48             croot.left = copyTree(root.left);
    49             croot.right = copyTree(root.right);
    50             return croot;
    51         }
    52     }
    53 }
  • 相关阅读:
    mysql view
    单点登录原理与简单实现
    复述记忆法
    英语细节锦集(基本时态的构成、元音辅音字母、)
    被动语态 动词的过去分词
    play后面加the不加the如何分辨
    正则表达式入门
    使用 lxml 中的 xpath 高效提取文本与标签属性值
    Android Studio 导入新工程项目
    winfrom Panel 问题
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5456393.html
Copyright © 2011-2022 走看看