1. 程式人生 > >JavaScript刷LeetCode -- 572. Subtree of Another Tree

JavaScript刷LeetCode -- 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.

二、題目大意

  給定一個二叉樹t,判斷它是否為二叉樹s的子樹,一個樹的子樹定義為:一個節點和該節點所有子樹組成的樹。

三、解題思路

  從子樹的定義可以將這道題轉化為s中是否存在以一個節點為根的樹是否與t相等的問題。

四、程式碼實現

const isSubtree = (s, t) => {

  if (!s) {
    return false
  }

  if (isSame(s, t)) {
    return true
  }

  return isSubtree(s.left, t) || isSubtree(s.right, t)

  function isSame (s, t) {
    if (!s && !t) {
      return true
    }
    if (!s || !t) {
      return false
    }
    if (s.val !== t.val) {
      return false
    }
    return isSame(s.left, t.left) && isSame(s.right, t.right)
  }
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。