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

Commitbf7597f

Browse files
committed
提供Javascript版本的《二叉搜索数的最近公共祖先》
1 parente719e4f commitbf7597f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,62 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
314314
```
315315

316316

317+
JavaScript版本
318+
>递归
317319
320+
```javascript
321+
/**
322+
* Definition for a binary tree node.
323+
* function TreeNode(val) {
324+
* this.val = val;
325+
* this.left = this.right = null;
326+
* }
327+
*/
328+
329+
/**
330+
*@param{TreeNode}root
331+
*@param{TreeNode}p
332+
*@param{TreeNode}q
333+
*@return{TreeNode}
334+
*/
335+
varlowestCommonAncestor=function(root,p,q) {
336+
if(root.val>p.val&&root.val>q.val)
337+
returnlowestCommonAncestor(root.left, p , q);
338+
elseif(root.val<p.val&&root.val<q.val)
339+
returnlowestCommonAncestor(root.right, p , q);
340+
return root;
341+
};
342+
```
343+
344+
>迭代
345+
346+
```javascript
347+
/**
348+
* Definition for a binary tree node.
349+
* function TreeNode(val) {
350+
* this.val = val;
351+
* this.left = this.right = null;
352+
* }
353+
*/
354+
355+
/**
356+
*@param{TreeNode}root
357+
*@param{TreeNode}p
358+
*@param{TreeNode}q
359+
*@return{TreeNode}
360+
*/
361+
varlowestCommonAncestor=function(root,p,q) {
362+
while(1) {
363+
if(root.val>p.val&&root.val>q.val)
364+
root=root.left;
365+
elseif(root.val<p.val&&root.val<q.val)
366+
root=root.right;
367+
else
368+
break;
369+
}
370+
return root;
371+
};
372+
```
318373

319374

320375
-----------------------

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp