104. Maximum Depth of Binary Tree
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.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
解法
DFS
深度优先的递归实现:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return 1 + max(left, right)
# or
class Solution:
def maxDepth(self, root: TreeNode) -> int:
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) \
if root else 0
BFS
广度优先需要借助队列实现,队列用于记录每一层的所有节点,每更新一层,深度就加一,当队列为空时说明不再有下一层节点,循环结束,返回深度。
class Solution:
def maxDepth(self, root: TreeNode) -> int:
depth = 0
level = [root] if root else []
while level:
depth += 1
queue = [] # named queue but not a real queue :)
for el in level:
if el.left:
queue.append(el.left)
if el.right:
queue.append(el.right)
level = queue
return depth
# a real queue solution
def maxDepth(self, root):
if not root:
return 0
tqueue, h = collections.deque(), 0
tqueue.append(root)
while tqueue:
nextlevel = collections.deque()
while tqueue:
front = tqueue.popleft()
if front.left:
nextlevel.append(front.left)
if front.right:
nextlevel.append(front.right)
tqueue = nextlevel
h += 1
return h
# a stack solution
def maxDepth(self, root):
if not root:
return 0
tstack,h = [root],0
#count number of levels
while tstack:
nextlevel = []
while tstack:
top = tstack.pop()
if top.left:
nextlevel.append(top.left)
if top.right:
nextlevel.append(top.right)
tstack = nextlevel
h+=1
return h
Last updated
Was this helpful?