• 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
            
    
  • 相关阅读:
    FreeMarker配置详解
    tab显示不同数据
    EL表达式可以直接放在url的“ ”里面
    js的搜索框
    js实现tab页面不同内容切换显示
    如何让html中的td文字只显示部分
    MobileNets: Open-Source Models for Efficient On-Device Vision
    LFW Face Database下载
    python遍历文件夹
    把cifar数据转换为图片
  • 原文地址:https://www.cnblogs.com/bush2582/p/11286551.html
Copyright © 2020-2023  润新知