add: 另一个树的子树

This commit is contained in:
yi-ge 2020-05-07 18:32:08 +08:00
parent 028efb9e7f
commit 431ac87901
3 changed files with 39 additions and 0 deletions

View File

@ -309,6 +309,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/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) - [合并K个排序链表](src/list/merge-k-sorted-lists.js)

View File

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

View File

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