100. 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.
# Definition for a binary tree node.
# 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 not p and not q: #p,q为空
return True
elif not p or not q: #p,q有一个为空,一个不为空
return False
elif p.val!=q.val: #p,q均不空,但是值不相等
return False
else:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
104. Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
算法思想:采用宽度优先搜索,一层层处理,在处理当前层时,最大深度+1,将队列中所有元素出队,并将这些元素的孩子节点全部入队,以此循环,直到队列为空。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
max_depth = 0
que = collections.deque()
que.append(root)
while que:
max_depth += 1
num_children = len(que)
for _ in range(num_children):
node = que.popleft()
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
return max_depth
网友评论