Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ceed453

Browse files
Merge pull request youngyangyang04#1130 from xiaofei-2020/tree29
添加(0235.二叉搜索树的最近公共祖先.md):增加typescript版本
2 parents f2f740f + 246bbe9 commit ceed453

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎problems/0235.二叉搜索树的最近公共祖先.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,39 @@ var lowestCommonAncestor = function(root, p, q) {
350350
};
351351
```
352352

353+
## TypeScript
354+
355+
> 递归法:
356+
357+
```typescript
358+
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
359+
if (root.val > p.val && root.val > q.val)
360+
return lowestCommonAncestor(root.left, p, q);
361+
if (root.val < p.val && root.val < q.val)
362+
return lowestCommonAncestor(root.right, p, q);
363+
return root;
364+
};
365+
```
366+
367+
> 迭代法:
368+
369+
```typescript
370+
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
371+
while (root !== null) {
372+
if (root.val > p.val && root.val > q.val) {
373+
root = root.left;
374+
} else if (root.val < p.val && root.val < q.val) {
375+
root = root.right;
376+
} else {
377+
return root;
378+
};
379+
};
380+
return null;
381+
};
382+
```
383+
384+
385+
353386

354387
-----------------------
355388
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /