# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: #如果树为空
return 0
level = 1
current_level = 1
stack = list()
stack.append(root)
while stack:
count = len(stack)
for i in range(count):
tmp = stack.pop(0)
if tmp.left or tmp.right:
if current_level == level:
level += 1
if tmp.left:
stack.append(tmp.left)
if tmp.right:
stack.append(tmp.right)
current_level +=1
return level
树-104. 二叉树的最大深度-PYTHON
最新推荐文章于 2024-02-14 09:06:29 发布