You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
163
+
164
+
For example,
165
+
166
+
Given n = 3, there are a total of 5 unique BST's.
167
+
\begin{Code}
168
+
1 3 3 2 1
169
+
\ / / / \ \
170
+
3 2 1 1 3 2
171
+
/ / \ \
172
+
2 1 2 3
173
+
\end{Code}
174
+
175
+
\subsubsection{Solution}
176
+
\begin{Code}
177
+
public int numTrees(int n) {
178
+
int[] dp = new int[n + 1];
179
+
dp[0] = 1;
180
+
181
+
for (int i = 1; i <= n; i++) {
182
+
for (int j = 0; j < i; j++) {
183
+
dp[i] += dp[j] * dp[i - j - 1];
184
+
}
185
+
}
186
+
187
+
return dp[n];
188
+
}
189
+
\end{Code}
190
+
191
+
\newpage
192
+
193
+
\section{Lowest Common Ancestor of a Binary Search Tree} %%%%%%%%%%%%%%%%%%%%%%
194
+
195
+
\subsubsection{Description}
196
+
197
+
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
198
+
199
+
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
200
+
\begin{Code}
201
+
_______6______
202
+
/ \
203
+
___2__ ___8__
204
+
/ \ / \
205
+
0 _4 7 9
206
+
/ \
207
+
3 5
208
+
\end{Code}
209
+
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
210
+
211
+
\subsubsection{Solution}
212
+
213
+
\begin{Code}
214
+
// 耗时9ms
215
+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
216
+
if (!checkExist(root, p) || !checkExist(root, q)) {
217
+
throw new IllegalArgumentException("Not exist!!");
Given a binary tree, determine if it is height-balanced.
257
+
258
+
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
0 commit comments