mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
0236二叉树的最近公共祖先JavaScript版本
This commit is contained in:
@ -310,7 +310,31 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
JavaScript版本:
|
||||
```javascript
|
||||
var lowestCommonAncestor = function(root, p, q) {
|
||||
// 使用递归的方法
|
||||
// 需要从下到上,所以使用后序遍历
|
||||
// 1. 确定递归的函数
|
||||
const travelTree = function(root,p,q) {
|
||||
// 2. 确定递归终止条件
|
||||
if(root === null || root === p||root === q) {
|
||||
return root;
|
||||
}
|
||||
// 3. 确定递归单层逻辑
|
||||
let left = travelTree(root.left,p,q);
|
||||
let right = travelTree(root.right,p,q);
|
||||
if(left !== null&&right !== null) {
|
||||
return root;
|
||||
}
|
||||
if(left ===null) {
|
||||
return right;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
return travelTree(root,p,q);
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user