zoukankan      html  css  js  c++  java
  • Unique Binary Search Trees II 解答

    Question

    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 

    Solution

    Key to the solution is to divide the problem into two sub-problems. Unlike "Unique Binary Search Trees", this problem is NP-hard.

     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 generateTreesHelper(1, n); 
    13     }
    14     private List<TreeNode> generateTreesHelper(int start, int end) {
    15         List<TreeNode> result = new ArrayList<TreeNode>();
    16         if (start > end) {
    17             result.add(null);
    18             return result;
    19         }
    20         for (int i = start; i <= end; i++) {
    21             List<TreeNode> lefts = generateTreesHelper(start, i - 1);
    22             List<TreeNode> rights = generateTreesHelper(i + 1, end);
    23             for (TreeNode left : lefts) {
    24                 for (TreeNode right : rights) {
    25                     TreeNode tmp = new TreeNode(i);
    26                     tmp.left = left;
    27                     tmp.right = right;
    28                     result.add(tmp);
    29                 }
    30             }
    31         }
    32         return result;
    33     }
    34 }
  • 相关阅读:
    Buffer -nodejs
    Tip提示框另类写法
    SASS入门
    界面设计必须要权衡的三个要素
    如何快速出稿一个优秀APP的构图
    如何画好一套线性图标
    Ui培训之如何设计极简三色图标
    移动APP设计国外资源总汇
    移动界面UI颜色设计
    APP专业视觉设计基础标准要求
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4825083.html
Copyright © 2011-2022 走看看