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.
算法思想:采用寬度優(yōu)先搜索表谊,一層層處理,在處理當前層時喉祭,最大深度+1养渴,將隊列中所有元素出隊,并將這些元素的孩子節(jié)點全部入隊泛烙,以此循環(huán)理卑,直到隊列為空。
# 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