Movatterモバイル変換


[0]ホーム

URL:


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

Commit53ce92f

Browse files
author
xeniaxie(xl)
committed
0235二叉搜索树的最近公共祖先Javascript版本
1 parent1e6265d commit53ce92f

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

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

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -312,8 +312,46 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
312312
}else {return findLeft}
313313
}
314314
```
315-
316-
315+
JavaScript版本:
316+
1. 使用递归的方法
317+
```javascript
318+
varlowestCommonAncestor=function(root,p,q) {
319+
// 使用递归的方法
320+
// 1. 使用给定的递归函数lowestCommonAncestor
321+
// 2. 确定递归终止条件
322+
if(root===null) {
323+
return root;
324+
}
325+
if(root.val>p.val&&root.val>q.val) {
326+
// 向左子树查询
327+
let left=lowestCommonAncestor(root.left,p,q);
328+
return left!==null&&left;
329+
}
330+
if(root.val<p.val&&root.val<q.val) {
331+
// 向右子树查询
332+
let right=lowestCommonAncestor(root.right,p,q);
333+
return right!==null&&right;
334+
}
335+
return root;
336+
};
337+
```
338+
2. 使用迭代的方法
339+
```javascript
340+
varlowestCommonAncestor=function(root,p,q) {
341+
// 使用迭代的方法
342+
while(root) {
343+
if(root.val>p.val&&root.val>q.val) {
344+
root=root.left;
345+
}elseif(root.val<p.val&&root.val<q.val) {
346+
root=root.right;
347+
}else {
348+
return root;
349+
}
350+
351+
}
352+
returnnull;
353+
};
354+
```
317355

318356

319357

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp