Subtree of Another Tree

easy tree dfs

Problem

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values as subRoot.

Walk every node n of root and ask "does the subtree rooted at n equal subRoot?". The inner check is a standard same-tree recursion.

Inputroot = [3,4,5,1,2], subRoot = [4,1,2]
Outputtrue

def is_subtree(root, sub_root):
    if root is None:
        return False
    if same(root, sub_root):
        return True
    return is_subtree(root.left, sub_root) or is_subtree(root.right, sub_root)

def same(a, b):
    if a is None and b is None: return True
    if a is None or b is None:  return False
    if a.val != b.val:           return False
    return same(a.left, b.left) and same(a.right, b.right)
function isSubtree(root, subRoot) {
  if (!root) return false;
  if (same(root, subRoot)) return true;
  return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}

function same(a, b) {
  if (!a && !b) return true;
  if (!a || !b) return false;
  if (a.val !== b.val) return false;
  return same(a.left, b.left) && same(a.right, b.right);
}
class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) return false;
        if (same(root, subRoot)) return true;
        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }
    boolean same(TreeNode a, TreeNode b) {
        if (a == null && b == null) return true;
        if (a == null || b == null) return false;
        if (a.val != b.val) return false;
        return same(a.left, b.left) && same(a.right, b.right);
    }
}
bool same(TreeNode* a, TreeNode* b) {
    if (!a && !b) return true;
    if (!a || !b) return false;
    if (a->val != b->val) return false;
    return same(a->left, b->left) && same(a->right, b->right);
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
    if (!root) return false;
    if (same(root, subRoot)) return true;
    return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
Time: O(n · m) worst case Space: O(h)