[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
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/4d5699cbde76
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞