zoukankan      html  css  js  c++  java
  • LeetCode Easy: 100. Same Tree

    一、题目

    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.

    比较两棵二叉树,看其是否相等。

    二、思路

    可以采用递归方式,分三种情况:

    1、两棵树均为空,返回True;

    2、两棵树一空一非空,返回False;

    3、两棵树的值相等,然后递归判断其子结点是否相等;

    三、代码

    #coding:utf-8
    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    class Solution:
        def isSameTree(self, p, q):
            """
            :type p: TreeNode
            :type q: TreeNode
            :rtype: bool
            """
            # if p == None and q == None:
            #     print('True')
            #     return True
            # elif p == None or q== None:
            #     print('False')
            #     return False
            # elif p.val == q.val:
            #     print(self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right))
            #     return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
            # else:
            #     print("False")
            #     return False
    
    #采用栈的方式,非递归 stack = [(p, q)] while stack: p, q = stack.pop() if p == None and q == None: continue if p == None or q == None: print('False') return False if p.val == q.val: stack.append((p.right, q.right)) stack.append((p.left, q.left)) else: print('False') return False print('True') return True if __name__ == '__main__': S = Solution() l1 = TreeNode(4) l2 = TreeNode(2) l3 = TreeNode(6) l4 = TreeNode(1) l5 = TreeNode(4) l6 = TreeNode(2) l7 = TreeNode(6) root1 = l1 l1.left = l2 l1.right = l3 root2 = l2 l2.left = l4 l2.right = l5 root3 = l1 l3.left = l6 l3.right = l7 #S.isSameTree(root1,root2) S.isSameTree(root1,root3)

      还有一种采用非递归的方式,来源于博客:https://blog.csdn.net/lilong_dream/article/details/22753227

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    从一个故障说说Java的三个BlockingQueue
    kafka producer源码
    Mock方法介绍
    async4j 普通用法、整合spring用法
    Spring中属性文件properties的读取与使用
    异步框架asyn4j的原理
    如何从线程返回信息——轮询、回调、Callable
    jdk 1.8 Executors
    java Iterator Fail-fast机制
    java的几种对象(PO,VO,DAO,BO,POJO)解释
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8708748.html
Copyright © 2011-2022 走看看