Skip to content

Commit

Permalink
finish 0572
Browse files Browse the repository at this point in the history
  • Loading branch information
benben6515 committed May 20, 2022
1 parent 91d0e35 commit 72e3d2b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ since 2021.10.10 / Benben
- 0242.Valid Anagram
- 0509.Fibonacci Number
- 0543.Diameter of Binary Tree
- 0572.Subtree of Another Tree
- 0704.Binary Search
- 0905.Sort Array By Parity
- 1694.Reformat Phone Number
Expand Down
35 changes: 35 additions & 0 deletions leetcode-easy/0572-subtree-of-another-tree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* 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} root
* @param {TreeNode} subRoot
* @return {boolean}
*/
var isSubtree = function(root, subRoot) {
if (root === null || subRoot === null) return false

const isSameTree = (n1, n2) => {
if (n1 === null && n2 === null) return true
if (n1 === null || n2 === null) return false
if (n1.val !== n2.val) return false
return isSameTree(n1.left, n2.left) && isSameTree(n1.right, n2.right)
}

const traverseRoot = (root, subRoot) => {
if (root === null) return subRoot === null
if (isSameTree(root, subRoot)) return true
return traverseRoot(root.left, subRoot) || traverseRoot(root.right, subRoot)
}

return traverseRoot(root, subRoot)
};

// 2022/05/21 done
// Runtime: 74 ms, faster than 98.49% of JavaScript online submissions for Subtree of Another Tree.
// Memory Usage: 49.6 MB, less than 18.31% of JavaScript online submissions for Subtree of Another Tree.

0 comments on commit 72e3d2b

Please sign in to comment.