递归:
# 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: TreeNode) -> int:
if root == None:
return 0
max_left=self.maxDepth(root.left)
max_right = self.maxDepth(root.right)
return max(max_left,max_right)+1
迭代:
我们把每一个结点及其对应的深度作为一条记录,使用栈这个数据结构来存储每条记录,遍历树的每一个结点,并用max_depth变量记录遍历到当前位置的最大深度,直到栈中为空为止。
class Solution:
"""
迭代法
"""
def maxDepth(self, root):
stack = [] # 定义一个空栈,栈中的元素是结点及其对应的深度
if root: # 如果根结点不为空
stack.append((root, 1)) # 则将根节点及其对应深度1组成的元组入栈
max_depth = 0 # 初始化最大深度为零
while stack: # 当栈非空时
tree_node, cur_depth = stack.pop() # 弹出栈顶结点及其对应的深度
if tree_node: # 如果该结点不为空
max_depth = max(max_depth, cur_depth) # 更新当前最大深度,如果该结点深度更大的话
stack.append((tree_node.left, cur_depth+1)) # 将该结点的左孩子结点及其对应深度压入栈中
stack.append((tree_node.right, cur_depth+1)) # 将该结点的右孩子结点及其对应深度压入栈中
return max_depth # 返回遍历结束后的最大深度
https://www.jianshu.com/p/e5160fa3af14