• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-04-03 15:27  乐晓东随笔  阅读(149)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3