zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    CentOS VPS
    Make 命令教程
    Nginx 学习
    字体对齐问题
    postman curl
    linux命令
    服务器
    操作系统
    nginx-1.15遇到无法加载php文件报404的问题
    thinkphp6.0框架下载与安装
  • 原文地址:https://www.cnblogs.com/seyjs/p/10585867.html
Copyright © 2011-2022 走看看