Subtree of Another Tree (Easy Facebook)

update May 11,2018 21:58

LeetCodearrow-up-right

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.

Basic Idea:

写一个 isSame 的 helper function,判断两个node所代表的是否是同样的树,然后递归调用。两层递归嵌套。

  • C++ Code:

update 2018-10-07 21:48:46

Update:Simpler java code

  • Java Code:

    更加简洁的写法,直接对比s的每个子树和t是否相等,不需要提前判断值是否相同。