Compare commits
2 Commits
05e950c2e4
...
da0e4f1359
Author | SHA1 | Date | |
---|---|---|---|
da0e4f1359 | |||
64941ec538 |
@ -318,6 +318,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
|||||||
- LeetCode 98. 验证二叉搜索树 https://leetcode-cn.com/problems/validate-binary-search-tree/
|
- LeetCode 98. 验证二叉搜索树 https://leetcode-cn.com/problems/validate-binary-search-tree/
|
||||||
- LintCode 95. 验证二叉查找树 https://www.lintcode.com/problem/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
|
||||||
|
|
||||||
- [另一个树的子树](src/tree/subtree-of-another-tree.js)
|
- [另一个树的子树](src/tree/subtree-of-another-tree.js)
|
||||||
|
|
||||||
- LeetCode 572. 另一个树的子树 https://leetcode-cn.com/problems/subtree-of-another-tree/
|
- LeetCode 572. 另一个树的子树 https://leetcode-cn.com/problems/subtree-of-another-tree/
|
||||||
|
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)
|
||||||
|
})
|
Reference in New Issue
Block a user