0236二叉树的最近公共祖先JavaScript版本

This commit is contained in:
xeniaxie(xl)
2021-06-26 21:12:39 +08:00
parent 178cf44b20
commit f3b21c7984

View File

@ -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);
};
```
-----------------------