zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):100 Same Tree

    题目来源


    https://leetcode.com/problems/same-tree/

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

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


    题意分析


    Input: twon binary tree

    Output: equal?

    Conditions:判断两个二叉树是不是相等。


    题目思路


    逐一遍历,看是否相等。


    AC代码(Python)

     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 
     8 class Solution(object):
     9     def isSameTree(self, p, q):
    10         """
    11         :type p: TreeNode
    12         :type q: TreeNode
    13         :rtype: bool
    14         """
    15         def dfs(p, q):
    16             if p == None and q != None:
    17                 return False
    18             if p != None and q == None:
    19                 return False
    20             if p == None and q == None:
    21                 return True
    22             if p.val != q.val:
    23                 return False
    24             return dfs(p.left, q.left) and dfs(p.right, q.right)
    25         
    26         return dfs(p,q)
    27         
  • 相关阅读:
    堆和栈的区别
    MyKTV点歌系统
    KTV音乐播放的实现
    继承与多态之汽车租赁系统
    使用集合组织相关数据
    用户登陆及异常的处理
    oracle函数详解
    Java中的多线程
    JAVA Map集合框架的使用
    Java中迭代器初深
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5502249.html
Copyright © 2011-2022 走看看