add: 二叉树的最近公共祖先
This commit is contained in:
parent
1227f993ae
commit
64941ec538
@ -305,6 +305,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
- LeetCode 98. 验证二叉搜索树 https://leetcode-cn.com/problems/validate-binary-search-tree/
|
||||
- LintCode 95. 验证二叉查找树 https://www.lintcode.com/problem/validate-binary-search-tree/
|
||||
|
||||
- [二叉树的最近公共祖先](src/tree/lowest-common-ancestor-of-a-binary-tree.js)
|
||||
|
||||
- LeetCode 236. 二叉树的最近公共祖先 https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
|
||||
- LintCode 88. 最近公共祖先 https://www.lintcode.com/problem/lowest-common-ancestor-of-a-binary-tree/description
|
||||
|
||||
## 链表
|
||||
|
||||
- [合并K个排序链表](src/list/merge-k-sorted-lists.js)
|
||||
|
20
src/tree/lowest-common-ancestor-of-a-binary-tree.js
Normal file
20
src/tree/lowest-common-ancestor-of-a-binary-tree.js
Normal file
@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* function TreeNode(val) {
|
||||
* this.val = val;
|
||||
* this.left = this.right = null;
|
||||
* }
|
||||
*/
|
||||
/**
|
||||
* @param {TreeNode} root
|
||||
* @param {TreeNode} p
|
||||
* @param {TreeNode} q
|
||||
* @return {TreeNode}
|
||||
*/
|
||||
export const lowestCommonAncestor = function (root, p, q) {
|
||||
if (!root || root === p || root === q) return root
|
||||
const left = lowestCommonAncestor(root.left, p, q)
|
||||
const right = lowestCommonAncestor(root.right, p, q)
|
||||
if ((left === p && right === q) || (left === q && right === p)) return root
|
||||
return left || right
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
import { lowestCommonAncestor } from '../../src/tree/lowest-common-ancestor-of-a-binary-tree'
|
||||
import Tree from './Tree'
|
||||
|
||||
test('二叉树的最近公共祖先', () => {
|
||||
const head = Tree.arrToTree([3, 5, 1, 6, 2, 0, 8, null, null, 7, 4])
|
||||
expect(lowestCommonAncestor(head, head.left, head.right)).toEqual(head)
|
||||
expect(lowestCommonAncestor(head, head.left, head.left.right.right)).toEqual(head.left)
|
||||
})
|
Loading…
Reference in New Issue
Block a user