• 15.leetcode100_same_tree


    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.

    给两个两叉树,写一个函数判断这两个两叉树是否相等。如果他们的结构相同,树杈的值相同,则认为这两个两叉树相同

    2.题目分析

    树杈结构与链表节点相同,所以要从链表的角度来看待问题

    3.解题思路

     1 # Definition for a binary tree node.
     2 # class TreeNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 class Solution(object):
     8     def isSameTree(self, p, q):
     9         """
    10         :type p: TreeNode
    11         :type q: TreeNode
    12         :rtype: bool
    13         """
    14         if p==None and q==None: #判断树杈的结构是否相同
    15             return True
    16         elif p==None or q==None:
    17             return False
    18         else:                   #判断值是否相同
    19             if p.val!=q.val:               
    20                 return False
    21             else:               #相同的话,再调用函数本身,判断下一级的树杈是否相同
    22                 return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)

    4.解题收获

    三天前就开始做这个题,今天终于弄明白了。一开始觉得树杈结构是一种规律的列表,于是用从遍历列表的角度来看问题,觉得这个题很困难。从正确的链表的角度来看,这个题就很容易了。还是题练得少,思维误区太多,多加锻炼吧ヾ(◍°∇°◍)ノ゙

  • 相关阅读:
    CTF简介
    最先与最后
    记一次某校版facemash的搭建
    ipv6入门
    win10开启IPv6的两种方法
    安装 Go 1.11 在 Ubuntu 18.04 & 16.04 LTS
    python开发者的AsyncIO
    Python 异步--Await the Future
    Python元类
    alias 和 unalias 命令
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8428632.html
Copyright © 2020-2023  润新知