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

Commitf3b21c7

Browse files
author
xeniaxie(xl)
committed
0236二叉树的最近公共祖先JavaScript版本
1 parent178cf44 commitf3b21c7

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

‎problems/0236.二叉树的最近公共祖先.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,31 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
310310
returnnil
311311
}
312312
```
313-
313+
JavaScript版本:
314+
```javascript
315+
varlowestCommonAncestor=function(root,p,q) {
316+
// 使用递归的方法
317+
// 需要从下到上,所以使用后序遍历
318+
// 1. 确定递归的函数
319+
consttravelTree=function(root,p,q) {
320+
// 2. 确定递归终止条件
321+
if(root===null|| root=== p||root=== q) {
322+
return root;
323+
}
324+
// 3. 确定递归单层逻辑
325+
let left=travelTree(root.left,p,q);
326+
let right=travelTree(root.right,p,q);
327+
if(left!==null&&right!==null) {
328+
return root;
329+
}
330+
if(left===null) {
331+
return right;
332+
}
333+
return left;
334+
}
335+
returntravelTree(root,p,q);
336+
};
337+
```
314338

315339

316340
-----------------------

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp