Tree

64. Subtree of Another Tree

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 of subRoot and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.

Examples

Example 1

Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true

Example 2

Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false

Constraints

  • The number of nodes in the root tree is in the range [1, 2000].
  • The number of nodes in the subRoot tree is in the range [1, 1000].
  • -10^4 <= root.val <= 10^4
  • -10^4 <= subRoot.val <= 10^4

Dadas las raices de dos arboles binarios root y subRoot, devuelve true si existe un subarbol de root con la misma estructura y valores de nodos que subRoot, y false en caso contrario.

Un subarbol de un arbol binario tree es un arbol que consiste en un nodo de tree y todos los descendientes de ese nodo. El arbol tree tambien se puede considerar como un subarbol de si mismo.

Ejemplos

Ejemplo 1

Entrada: root = [3,4,5,1,2], subRoot = [4,1,2]
Salida: true

Ejemplo 2

Entrada: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Salida: false

Restricciones

  • El numero de nodos en el arbol root esta en el rango [1, 2000].
  • El numero de nodos en el arbol subRoot esta en el rango [1, 1000].
  • -10^4 <= root.val <= 10^4
  • -10^4 <= subRoot.val <= 10^4
subtree_of_another_tree.py
# Subtree of Another Tree
# Given two binary trees, check if subRoot is a subtree of root.
# A subtree must have the exact same structure and node values.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

# Check if two trees are identical
def same_tree(p, q):
    if not p and not q:
        return True
    if not p or not q:
        return False
    return (p.val == q.val and
            same_tree(p.left, q.left) and
            same_tree(p.right, q.right))

# Check if subRoot exists as a subtree in root
def is_subtree(root, sub_root):
    if not root:
        return False
    if same_tree(root, sub_root):
        return True
    return is_subtree(root.left, sub_root) or is_subtree(root.right, sub_root)

# Example 1: root = [3,4,5,1,2], subRoot = [4,1,2] -> true
root1 = TreeNode(3, TreeNode(4, TreeNode(1), TreeNode(2)), TreeNode(5))
sub1 = TreeNode(4, TreeNode(1), TreeNode(2))
print(is_subtree(root1, sub1))  # True

# Example 2: root = [3,4,5,1,2(->0),null,null], subRoot = [4,1,2] -> false
root2 = TreeNode(3, TreeNode(4, TreeNode(1), TreeNode(2, TreeNode(0))), TreeNode(5))
sub2 = TreeNode(4, TreeNode(1), TreeNode(2))
print(is_subtree(root2, sub2))  # False
Keyboard shortcuts
h Previous problem
l Next problem
Esc Back to index
? Toggle this help