Newton's Apple
InterviewTime limit1sMemory limit128 MB
Parse two binary trees from post-order tokens with nil markers, then decide whether one can be turned into the other by swapping left and right children at any nodes.
- Level
Medium6 of 10
- Topics
- Tree, Recursion, DFS, Implementation
- Solved
- No attempts yet
Problem
Two binary trees and are said to be equivalent if one of the following holds.
- Both trees are empty. Or
- The two roots hold the same value, and at least one of the following is true.
- (a) The left subtree of is equivalent to the left subtree of , and the right subtree of is equivalent to the right subtree of . Or
- (b) The left subtree of is equivalent to the right subtree of , and the right subtree of is equivalent to the left subtree of .
In other words, if you are allowed to freely swap the left and right subtree at every node, two trees are equivalent when they can be made identical in both shape and node values.
Given two binary trees, write a program that determines whether they are equivalent.
Input
The first line contains the number of test cases .
Each test case consists of two lines, and each line describes one tree to compare.
Each tree is given in post-order. An empty subtree is written as nil, and every node's data is a single uppercase letter. Each line always ends with end.
For example, one tree written in post-order looks like this.
nil nil nil G F nil nil C nil nil E nil D B A end
Output
For each test case, print true if the two trees are equivalent and false otherwise, one result per line.