572_Subtree of Another Tree
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could 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.
Solution 1: recursive
我们先从s的根结点开始,跟t比较,如果两棵树完全相同,那么返回true,否则就分别对s的左子结点和右子结点调用递归再次来判断是否相同,只要有一个返回true了,就表示可以找得到。
Time complexity: O(m*n). m is the number of nodes in s, n is the number of nodes in t.
Space complexity: O(n).
Solution 2: serialize tree and compare
下面这道题的解法用到了之前那道 Serialize and Deserialize Binary Tree 的解法,思路是对s和t两棵树分别进行序列化,各生成一个字符串,如果t的字符串是s的子串的话,就说明t是s的子树,但是需要注意的是,为了避免出现[12], [2], 这种情况,虽然2也是12的子串,但是[2]却不是[12]的子树,所以我们再序列化的时候要特殊处理一下,就是在每个结点值前面都加上一个字符,比如 在前面加‘^’ 后面加‘#’ 来分隔开,那么[12]序列化后就是"^12#",而[2]序列化之后就是"^2#",这样就可以完美的解决之前的问题了。最低端的空leaf 赋值 ‘$’.
一定要用Preorder traverase. 因为要保证根点下面的所有点都相同。
Last updated