572 Subtree of Another Tree
Given two non-empty binary treessandt, check whether treethas exactly the same structure and node values with a subtree ofs. A subtree ofsis a tree consists of a node insand all of this node's descendants. The treescould also be considered as a subtree of itself.
Example 1: Given tree s:
Given tree t:
Return true
, because t has the same structure and node values with a subtree of s.
Example 2: Given tree s:
Given tree t:
Return false
The Idea: The idea is to perform some kind of traversal that is non unique to both trees. The problem then just simplifies into checking if tree t has a sub-traversal as tree s. In order words, return true if tree t contains a subarray in tree s. The only tricky part to this is understanding that we want to capture complete subtrees. In other words, both sequences must have the same sequence of null terminators. This is why we append unique characters '$' and '#' for the left and right null terms.
Complexity: O(n^2) time O(n) space (can be reduced to O(n) time with either ukkonens or KMP string matching algorithm)
Last updated