Subtree of Another Tree

Given two non-empty binary treessandt, check whether treethas exactly the same structure and node values with a subtree ofs. A subtree ofsis a tree consists of a node insand all of this node's descendants. The treescould 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:

Return

false

Solution 1:

Solution 2:

Last updated

Was this helpful?