
# 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
"""
stack = []
if root is not None:
stack.append((1, root))
depth = 0
while stack != []:
current_depth, root = stack.pop()
if root is not None:
depth = max(depth, current_depth)
stack.append((current_depth + 1, root.left))
stack.append((current_depth + 1, root.right))
return depth
1.append是可以添加元组的,而且元组是可以直接拆开赋值,元组和列表的区别就是值不可改变,当你不希望别人改变你列表中的数值的时候可以使用元组
2.从递归的思想出发,每步可以简单理解为找左子树和右子树中最大的depth
3.数据结构高分笔记的图的深度优先搜索算法可以看来参考
4.rtype:是返回类型缩写
本文详细解析了计算二叉树最大深度的算法实现,采用迭代方式通过栈结构进行节点深度的遍历与记录,提供了Python代码示例,并对比了元组与列表的特性,适合初学者理解二叉树的深度优先搜索。
464

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



