Compare commits

..

2 Commits

Author SHA1 Message Date
da0e4f1359 add: 二叉树的最近公共祖先 2020-05-10 15:31:25 +08:00
64941ec538 add: 二叉树的最近公共祖先 2020-05-10 15:30:48 +08:00
3 changed files with 33 additions and 0 deletions

View File

@ -318,6 +318,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
- [另一个树的子树](src/tree/subtree-of-another-tree.js)
- LeetCode 572. 另一个树的子树 https://leetcode-cn.com/problems/subtree-of-another-tree/

View 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
}

View File

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