0572. Subtree of Another Tree

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 s and t, determine whether t is a subtree of s 🌲.
  • This problem is relatively simple. Recursively check the following 3 cases in order: the first case is that s and t are two completely identical trees; the second case is that t is a subtree of the left subtree of s; the third case is that t is a subtree of the right subtree of s. 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
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文