From 431ac87901000ee9fe8cec3bbbb9750bf522ee2a Mon Sep 17 00:00:00 2001 From: yi-ge Date: Thu, 7 May 2020 18:32:08 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E5=8F=A6=E4=B8=80=E4=B8=AA=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E5=AD=90=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ src/tree/subtree-of-another-tree.js | 27 +++++++++++++++++++++++ test/tree/subtree-of-another-tree.test.js | 7 ++++++ 3 files changed, 39 insertions(+) create mode 100644 src/tree/subtree-of-another-tree.js create mode 100644 test/tree/subtree-of-another-tree.test.js diff --git a/README.md b/README.md index d0bce6a..cf7ff98 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,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/subtree-of-another-tree.js) + + - LeetCode 572. 另一个树的子树 https://leetcode-cn.com/problems/subtree-of-another-tree/ + - LintCode 1165. 另一个树的子树 https://www.lintcode.com/problem/subtree-of-another-tree/description + ## 链表 - [合并K个排序链表](src/list/merge-k-sorted-lists.js) diff --git a/src/tree/subtree-of-another-tree.js b/src/tree/subtree-of-another-tree.js new file mode 100644 index 0000000..121578b --- /dev/null +++ b/src/tree/subtree-of-another-tree.js @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} s + * @param {TreeNode} t + * @return {boolean} + */ +export const isSubtree = function (s, t) { + if (!s && t) { + return false + } + + const linkNode = function (node, target) { + if ((!node && target) || (node && !target)) return false + if (!node && !target) return true + + return node.val === target.val ? linkNode(node.left, target.left) && linkNode(node.right, target.right) : false + } + + return linkNode(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t) +} diff --git a/test/tree/subtree-of-another-tree.test.js b/test/tree/subtree-of-another-tree.test.js new file mode 100644 index 0000000..bb54e19 --- /dev/null +++ b/test/tree/subtree-of-another-tree.test.js @@ -0,0 +1,7 @@ +import { isSubtree } from '../../src/tree/subtree-of-another-tree' +import Tree from './Tree' + +test('另一个树的子树', () => { + expect(isSubtree(Tree.arrToTree([3, 4, 5, 1, 2]), Tree.arrToTree([4, 1, 2]))).toBe(true) + expect(isSubtree(Tree.arrToTree([3, 4, 5, 1, 2, null, null, null, null, 0]), Tree.arrToTree([4, 1, 2]))).toBe(false) +})