• 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 }
  • 相关阅读:
    读《持续交付2.0》
    “兼职”运维的常用命令
    技术管理者怎样跳出“泥潭”
    使用RabbitMQ实现接口补偿
    dotNET Core 中怎样操作 AD?
    dotNET Core实现分布式环境下的流水号唯一
    Git 远程仓库
    分之管理
    git 基本操作----git diff
    git 基本操作----git reset、log
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4825083.html
Copyright © 2020-2023  润新知