[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
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,766评论 0 33
  • 来自布拉格的年轻设计师Filip Hodas的日常作品,他通过平面软件将几何形式与自然场景联系起来,画面感前卫十足...
    美术视觉阅读 560评论 0 1
  • 每天连续十五个小时的工作,一切思索无法付诸笔端的心烦意乱。匆忙撇下一笔,以图“交差”的心态。 向点击的朋友...
    水塘湾阅读 227评论 0 0
  • 齐桓公问管仲,作为国君最要重视的是什么?管仲说是天。齐桓公抬头看天。管仲告诉他:这里所说的天,不是苍苍莽莽的天空,...
    二班班阅读 274评论 0 0
  • 1、 长安城外有一个小村庄叫林村,因为这里离官道比较远,所以平常比较安静,今天村子里却格外热闹,因为这里正在办...
    西城西月阅读 342评论 0 0