0572. Subtree of Another Tree

# 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:

``````     3
/ \
4   5
/ \
1   2
``````

Given tree t:

``````   4
/ \
1   2
``````

Return true, because t has the same structure and node values with a subtree of s.

Example 2:

Given tree s:

``````     3
/ \
4   5
/ \
1   2
/
0
``````

Given tree t:

``````   4
/ \
1   2
``````

Return false.

## 解题思路 #

• 给出 2 棵树 `s``t`，要求判断 `t` 是否是 `s` 的子树🌲。
• 这一题比较简单，针对 3 种情况依次递归判断，第一种情况 `s``t` 是完全一样的两棵树，第二种情况 `t``s` 左子树中的子树，第三种情况 `t``s` 右子树中的子树。第一种情况判断两棵数是否完全一致是第 100 题的原题。

## 代码 #

``````
package leetcode

/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func isSubtree(s *TreeNode, t *TreeNode) bool {
if isSameTree(s, t) {
return true
}
if s == nil {
return false
}
if isSubtree(s.Left, t) || isSubtree(s.Right, t) {
return true
}
return false
}

``````

Apr 8, 2023