#C14557. Identical Binary Trees from Preorder Traversal
Identical Binary Trees from Preorder Traversal
Identical Binary Trees from Preorder Traversal
You are given two binary trees in the form of their preorder traversals. Each traversal is represented as a sequence of values, where null indicates an empty node. Two trees are considered identical if they have the same structure and the corresponding nodes have the same values.
The preorder traversal of a binary tree is defined recursively as follows:
$$Preorder(Tree) = \begin{cases} [] & \text{if the tree is empty}, \ [ root, \; Preorder(left), \; Preorder(right) ] & \text{otherwise.} \end{cases} $$Your task is to determine whether the two given binary trees are identical.
inputFormat
The input consists of two lines:
- The first line contains a space-separated list of values representing the preorder traversal of the first binary tree.
- The second line contains a space-separated list of values representing the preorder traversal of the second binary tree.
Each value is either an integer or the string null
(in lowercase) which represents an empty node. An empty line represents an empty tree.
outputFormat
Output a single line: True
if the trees are identical, and False
otherwise.
1 2 null null 3 null null
1 2 null null 3 null null
True