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
一定要用Preorder traverase. 因为要保证根点下面的所有点都相同。
Last updated
Was this helpful?