From 64941ec53845cd72f6646df1e4dfda2037c267a5 Mon Sep 17 00:00:00 2001 From: yige Date: Sun, 10 May 2020 15:30:48 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ ...lowest-common-ancestor-of-a-binary-tree.js | 20 +++++++++++++++++++ ...t-common-ancestor-of-a-binary-tree.test.js | 8 ++++++++ 3 files changed, 33 insertions(+) create mode 100644 src/tree/lowest-common-ancestor-of-a-binary-tree.js create mode 100644 test/tree/lowest-common-ancestor-of-a-binary-tree.test.js diff --git a/README.md b/README.md index 07c1b10..8ab20ce 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/tree/lowest-common-ancestor-of-a-binary-tree.js b/src/tree/lowest-common-ancestor-of-a-binary-tree.js new file mode 100644 index 0000000..2014c09 --- /dev/null +++ b/src/tree/lowest-common-ancestor-of-a-binary-tree.js @@ -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 +} diff --git a/test/tree/lowest-common-ancestor-of-a-binary-tree.test.js b/test/tree/lowest-common-ancestor-of-a-binary-tree.test.js new file mode 100644 index 0000000..b7a62d3 --- /dev/null +++ b/test/tree/lowest-common-ancestor-of-a-binary-tree.test.js @@ -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) +})