zoukankan      html  css  js  c++  java
  • 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.解题收获

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

  • 相关阅读:
    Single Number II
    Pascal's Triangle
    Remove Duplicates from Sorted Array
    Populating Next Right Pointers in Each Node
    Minimum Depth of Binary Tree
    Unique Paths
    Sort Colors
    Swap Nodes in Pairs
    Merge Two Sorted Lists
    Climbing Stairs
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8428632.html
Copyright © 2011-2022 走看看