跳到主要内容

100. 相同的树 [easy]

100. 相同的树 [easy]

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

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入:       1         1
/ \ / \
2 3 2 3

[1,2,3], [1,2,3]

输出: true

示例 2:

输入:      1          1
/ \
2 2

[1,2], [1,null,2]

输出: false

示例 3:

输入:       1         1
/ \ / \
2 1 1 2

[1,2,1], [1,1,2]

输出: false

通过次数102,106 | 提交次数175,319

Second Try [golang]

2020-08-07

每日一题打卡, go语言练手


/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/


func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == nil {
return q == nil
}

if q == nil {
return p == nil
}

if p.Val != q.Val {
return false
}

return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)

  • 执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
  • 内存消耗:2.1 MB, 在所有 Go 提交中击败了9.21%的用户

First Try

2020-07-17

递归是最吼的

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p is None:
return q is None
if q is None:
return p is None

if p.val != q.val:
return False

return self.isSameTree(p.left, q.left) \
and self.isSameTree(p.right, q.right)
  • 执行用时:12 ms, 在所有 Python 提交中击败了98.27%的用户
  • 内存消耗:12.7 MB, 在所有 Python 提交中击败了33.33%