📘
Subtree of Another Tree
EasyTrees & BFS
Given two binary trees root and subRoot (as level-order arrays), return True if subRoot is a subtree of root.
A subtree is a node and all its descendants matching exactly.
Example:
Input:
3,4,5,1,2 4,1,2
Output:
True
Reasoning:
- The binary tree
rootis constructed from the level-order array: 3,4,5,1,2, resulting in a tree with 3 as the root, 4 and 5 as its children, and 1 and 2 as children of 4. - The binary tree
subRootis constructed from the level-order array: 4,1,2, resulting in a tree with 4 as the root and 1 and 2 as its children. - We then check if
subRootis a subtree ofrootby comparing the structure and node values ofsubRootwith the corresponding subtree ofrootrooted at node 4. - Since the subtree of
rootrooted at node 4 has the same structure and node values assubRoot, we conclude thatsubRootis a subtree ofroot, resulting in an output ofTrue.
Constraints:
- 1 <= nodes in root <= 2000
- 1 <= nodes in subRoot <= 1000
- -10^4 <= Node.val <= 10^4
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.