From 6a7cdb42a03217e0e7a99191736f0720e2c0f9ae Mon Sep 17 00:00:00 2001 From: quyan Date: Mon, 15 Apr 2019 23:51:41 +0800 Subject: [PATCH] =?UTF-8?q?Update=20Leetcode=20=E9=A2=98=E8=A7=A3=20-=20?= =?UTF-8?q?=E5=88=86=E6=B2=BB.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/notes/Leetcode 题解 - 分治.md | 51 ++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/docs/notes/Leetcode 题解 - 分治.md b/docs/notes/Leetcode 题解 - 分治.md index 7c37b9fa..fe7c2088 100644 --- a/docs/notes/Leetcode 题解 - 分治.md +++ b/docs/notes/Leetcode 题解 - 分治.md @@ -1,5 +1,6 @@ * [1. 给表达式加括号](#1-给表达式加括号) +* [2. 不同的二叉搜索树II](#2-不同的二叉搜索树II) @@ -48,6 +49,56 @@ public List diffWaysToCompute(String input) { } ``` +# 2. 不同的二叉搜索树II + +[95. Unique Binary Search Trees II (Medium)](https://leetcode.com/problems/unique-binary-search-trees-ii/description/) + +```html +Input: 3 +Output: +[ + [1,null,3,2], + [3,2,null,1], + [3,1,null,null,2], + [2,1,3], + [1,null,2,null,3] +] +Explanation: +The above output corresponds to the 5 unique BST's shown below: + + 1 3 3 2 1 + \ / / / \ \ + 3 2 1 1 3 2 + / / \ \ + 2 1 2 3 +``` + +```java +public List generateTrees(int n) { + return generateSubtrees(1, n); +} + +private List generateSubtrees(int s, int e) { + List res = new LinkedList(); + if (s > e) { + res.add(null); + return res; + } + for (int i = s; i <= e; ++i) { + List leftSubtrees = generateSubtrees(s, i - 1); + List rightSubtrees = generateSubtrees(i + 1, e); + for (TreeNode left : leftSubtrees) { + for (TreeNode right : rightSubtrees) { + TreeNode root = new TreeNode(i); + root.left = left; + root.right = right; + res.add(root); + } + } + } + return res; +} +```