95.unique-binary-search-trees-ii

Description:

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

Similar Question: 96.unique-binary-search-trees

Binary Search Tree(BST):

  • Key(L)<Key(Current)<Key(R)
  • Both subtrees of each node are also BSTs

Appropriate Answer (Divide-and-conquer):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php

namespace LeetCode\UniqueBinarySearchTreesII;

/**
* Definition for a binary tree node.
*/
// class TreeNode
// {
// public $val = null;
// public $left = null;
// public $right = null;
// function __construct($val = 0, $left = null, $right = null)
// {
// $this->val = $val;
// $this->left = $left;
// $this->right = $right;
// }
// }

class Solution
{
/**
* @param int $n
* @return TreeNode[]
*/
public function generateTrees($n)
{
$numbers = range(1, $n);
return $this->generateTreesByNumbers($numbers);
}

/**
* @param int[] $originalNumbers
* @return array
*/
private function generateTreesByNumbers($originalNumbers)
{
if (count($originalNumbers) == 0) {
return [null];
}

if (count($originalNumbers) == 1) {
return [new TreeNode(array_pop($originalNumbers))];
}

$result = [];
//[1,2,3] => (1, [2,3]) (2, [1,3]) (3, [1,2])
foreach ($originalNumbers as $key => $val) {
$currentNumbers = $originalNumbers;
unset($currentNumbers[$key]);
$otherNumbers = $currentNumbers;

$result = array_merge($result, $this->binarySearch($val, $otherNumbers));
}

return $result;
}

/**
* @param int $val
* @param int[] $otherNumbers
* @return TreeNode[]
*/
private function binarySearch($val, $otherNumbers)
{
$smallerNumbers = array_filter($otherNumbers, function ($otherNumber) use ($val) {
return $otherNumber < $val;
});

$biggerNumbers = array_filter($otherNumbers, function ($otherNumber) use ($val) {
return $otherNumber > $val;
});

$smallerTrees = $this->generateTreesByNumbers($smallerNumbers);
$biggerTrees = $this->generateTreesByNumbers($biggerNumbers);

$trees = [];
foreach ($smallerTrees as $aSmallerTree) {
foreach ($biggerTrees as $aBiggerTree) {
$tree = new TreeNode($val, $aSmallerTree, $aBiggerTree);
$trees[] = $tree;
}
}

return $trees;
}
}

ʕ •ᴥ•ʔ:由 linsheng 提供的解法。

Share