zoukankan      html  css  js  c++  java
  • 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
            
    
  • 相关阅读:
    extjs grid renderer用法
    spket对Extjs4的支持方法 eclipse插件spket安装 extjs4 提示
    Delphi关于多线程同步的一些方法 zb
    指针学习(一) zb
    struts2中action实现ModelDriven后无法返回json的问题
    前端css编写规范
    javascript 原型链
    chrome bug
    浏览器缓存
    RegExp
  • 原文地址:https://www.cnblogs.com/bush2582/p/11286551.html
Copyright © 2011-2022 走看看