【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的遍历路径的子串即可。

代码如下:

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    path = ''
    def traverse(self,node,direction):
        if node == None:
            return
        self.path += (direction + 'V' + str(node.val))  #节点值加上V前缀
        if node.left != None:
            self.traverse(node.left,'L') #左右节点分别加上标识
        else:
            self.path += 'LN'
        if node.right != None:
            self.traverse(node.right,'R')
        else:
            self.path += 'RN'
    def isSubtree(self, s, t):
        """
        :type s: TreeNode
        :type t: TreeNode
        :rtype: bool
        """
        self.path = ''
        self.traverse(s,'')
        self.path += '#'
        self.traverse(t,'')
        pl = self.path.split('#')
        #print self.path
        return pl[0].find(pl[1]) != -1
原文地址:https://www.cnblogs.com/seyjs/p/10585867.html