Leetcode 100 相同的树
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
leetcode100 相同的树
题目难度:简单
首先想到的就是递归的方法,没什么难度,代码如下:
# 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 == None and q ==None: #判断是否叶节点
return True
while p!=None and q!=None:
if q.val == p.val:
return (self.isSameTree(q.left, p.left) and self.isSameTree(q.right, p.right))
else:
return False
return False
代码时间复杂度为 O ( n ) O(n) O(n), 其中N是树的节点数。时间20ms,打败66.15%
看到了最优的代码:
# 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
"""
# p and q are both None
if not p and not q: # p == None 等价于 not p
return True
# one of p and q is None
if not q or not p:
return False
if p.val != q.val:
return False
return self.isSameTree(p.right, q.right) and \
self.isSameTree(p.left, q.left)
收获:更简单的判断条件
leetcode 226
深度优先吧,其实就是一个遍历,先序与后序都可以
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
self.invertTree(root.left)
self.invertTree(root.right)
root.left, root.right = root.right, root.left
return root