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.
这题要返回树的最大深度~ 递归解法很简单
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root is None: return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1还有一种非递归解法,采用层序遍历
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root is None: return 0
depth = 1
queue = [root, None]
while len(queue) > 1:
node = queue.pop(0)
if node is None:
depth += 1
queue.append(None)
continue
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
本文介绍了一种计算二叉树最大深度的方法,通过两种不同的实现方式:递归法和层序遍历法,来解决这个问题。递归法简单直观,而层序遍历法则适用于更广泛的树结构。
1409

被折叠的 条评论
为什么被折叠?



