zoukankan      html  css  js  c++  java
  • 95. Unique Binary Search Trees II

    Given an integer 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

    题目含义:给定一个字符串,给出所有可能的二叉树(左子树中所有节点都小于根节点,右子树所有节点都大于根节点)

    思路:
    1. 每一次都在一个范围内随机选取一个结点作为根。 
    2. 每选取一个结点作为根,就把树切分成左右两个子树,直至该结点左右子树为空。

     1     public List<TreeNode> generateTrees(int n) {
     2         if(n < 1)return new ArrayList<TreeNode>();
     3         return createTree(1, n);
     4     }
     5     
     6     public List<TreeNode> createTree(int start, int end) {
     7         List<TreeNode> res = new ArrayList();
     8         if(start > end) {
     9             res.add(null);
    10             return res;
    11         }
    12         for(int i = start; i <= end; i ++) {
    13             List<TreeNode> leftChild = createTree(start, i - 1);
    14             List<TreeNode> rightChild = createTree(i + 1, end);
    15             for(TreeNode left : leftChild) {
    16                 for(TreeNode right : rightChild) {
    17                     TreeNode root = new TreeNode(i);
    18                     root.left = left;
    19                     root.right = right;
    20                     res.add(root);
    21                 }
    22             }
    23         }
    24         return res;
    25     }
  • 相关阅读:
    状态管理cookie 案例
    JavaScript对象(document对象 图片轮播)
    JavaScript对象(窗口对象 定时器对象 )
    JavaScript对象(正则表达式,Date对象,function对象 arguments对象)
    CSS概述<选择器总结>
    HTML表单
    Web表格
    JDBC项目实践
    JDBC获取表的主键
    JDBC中DAO事务函数模版
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7691201.html
Copyright © 2011-2022 走看看