• 100. Same Tree


    100. Same Tree

    1 题目

    1. Given two binary trees, write a function to check if they are the same or not.

      Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

      Example 1:

      Input:     1         1
                /        / 
               2   3     2   3
      
              [1,2,3],   [1,2,3]
      
      Output: true
      

      Example 2:

      Input:     1         1
                /           
               2             2
      
              [1,2],     [1,null,2]
      
      Output: false
      

      Example 3:

      Input:     1         1
                /        / 
               2   1     1   2
      
              [1,2,1],   [1,1,2]
      
      Output: false
      

    2 解题 && 思路

    对2棵树分别做前序遍历,然后把前序的字符串比较。注意左右子树是空,需要特殊标记。

    3. 实现

    # 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):
        def dlr(self,tree,dirlist):
            if tree is None :
                return 
            if tree.left is not None :
                self.dlr(tree.left,dirlist)
            else:
                dirlist.append(-2)
            dirlist.append(tree.val)
            if tree.right is not None :
                self.dlr(tree.right,dirlist)
            else:
                dirlist.append(-1)
            
        
        def isSameTree(self, p, q):
            """
            :type p: TreeNode
            :type q: TreeNode
            :rtype: bool
            """
            p_list = []
            q_list = []
    
            self.dlr(p,p_list)
            self.dlr(q,q_list)
            p_str=""
            q_str=""
            for e in p_list:
                p_str = p_str+str(e)
            for e in q_list:
                q_str = q_str+str(e)
     
            return p_str == q_str
            
    
  • 相关阅读:
    [CF1336C] Kaavi and Magic Spell
    [CF1338C] Perfect Triples
    [CF1353F] Decreasing Heights
    [CF1442B] Identify the Operations
    [CF1354E] Graph Coloring
    [CF1364D] Ehab's Last Corollary
    php-fpm和fastcgi的区别
    phpredis实现互斥锁
    关于lnmp情况下PHP单线程的理解
    客户端断开链接以后 PHP执行过程实测
  • 原文地址:https://www.cnblogs.com/bush2582/p/11286551.html
Copyright © 2020-2023  润新知