572. Subtree of Another Tree
2021-11-24 本文已影响0人
jluemmmm
- Runtime: 155 ms, faster than 13.96%
- Memory Usage: 45.8 MB, less than 46.49%
- 时间复杂度O(n),空间复杂度O(n)
/**
* 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) return false;
if (isSameTree(root, subRoot)) return true;
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
};
var isSameTree = function(a, b) {
if (!a && !b) return true;
if (!a || !b) return false;
return a.val === b.val && isSameTree(a.left, b.left) && isSameTree(a.right, b.right);
}