[LeetCode By Go 67]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相等。因此遍歷s,所有s的子樹和t相比,如果有相等的就說明t是s的子樹
注意
找到子樹后就不再進行遍歷

if subTree {
        return 
}

代碼

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isTreeEqual(s *TreeNode, t *TreeNode) bool {
    if nil == s && nil == t {
        return true
    } else if nil != s && nil == t {
        return false
    } else if nil == s && nil != t {
        return false
    }

    if s.Val != t.Val {
        return false
    }
    if !isTreeEqual(s.Left, t.Left) {
        return false
    }
    if !isTreeEqual(s.Right, t.Right) {
        return false
    }

    return true
}

var subTree bool

func travelTree(s *TreeNode, t *TreeNode)  {
    //already find subtree
    if subTree {
        return 
    }
    
    if nil == s {
        return
    }

    if isTreeEqual(s, t) {
        subTree = true
        return
    }

    travelTree(s.Left, t)
    travelTree(s.Right, t)
}

func isSubtree(s *TreeNode, t *TreeNode) bool {
    subTree = false

    travelTree(s, t)
    return subTree
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,916評論 0 33
  • 來自布拉格的年輕設計師Filip Hodas的日常作品,他通過平面軟件將幾何形式與自然場景聯(lián)系起來,畫面感前衛(wèi)十足...
    美術視覺閱讀 604評論 0 1
  • 每天連續(xù)十五個小時的工作,一切思索無法付諸筆端的心煩意亂。匆忙撇下一筆,以圖“交差”的心態(tài)。 向點擊的朋友...
    水塘灣閱讀 262評論 0 0
  • 齊桓公問管仲,作為國君最要重視的是什么?管仲說是天。齊桓公抬頭看天。管仲告訴他:這里所說的天,不是蒼蒼莽莽的天空,...
    二班班閱讀 328評論 0 0
  • 1、 長安城外有一個小村莊叫林村,因為這里離官道比較遠,所以平常比較安靜,今天村子里卻格外熱鬧,因為這里正在辦...
    西城西月閱讀 368評論 0 0

友情鏈接更多精彩內容