Description
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.
分析
题目的意思是:判断树t是否是树s的子树。
- 子树必须是叶结点开始的,中间某个部分的不能算是子树,那么是不是从s的某个节点开始,跟t的所有结构都一样,这个问题就转换成了判断两棵树是否相同,也就是Same Tree的问题了。我们先从s的根节点出发,跟t比较,如果两棵树完全相同,那么返回true,否则就分别对左子结点和右子结点调用递归来判断是否相同,只要一个返回true了,就表示可以找得到。
代码
参考文献
[LeetCode] Subtree of Another Tree 另一个树的子树