572. Subtree of Another Tree #
Problem #
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.
Problem Summary #
Given two non-empty binary trees s and t, check whether s contains a subtree with exactly the same structure and node values as t. A subtree of s includes a node in s and all of this node’s descendants. s can also be considered a subtree of itself.
Solution Approach #
- Given 2 trees
sandt, determine whethertis a subtree ofs🌲. - This problem is relatively simple. Recursively check the following 3 cases in order: the first case is that
sandtare two completely identical trees; the second case is thattis a subtree of the left subtree ofs; the third case is thattis a subtree of the right subtree ofs. Determining whether two trees are completely identical in the first case is the original problem of Problem 100.
Code #
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
}