难度:简单
题目描述:
思路总结:思路尼玛,多来点这种题,好有时间做剑指Offer。PS:这套模板实际上就是一个前序遍历的模板,思路很有限。
题解一:(递归)
# 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 not root:return 0
res = 0
def helper(node, level):
if not node.left and not node.right:
nonlocal res
res = max(level, res)
if node.left:
helper(node.left, level+1)
if node.right:
helper(node.right, level+1)
helper(root, 1)
return res
题解一结果:
题解二:(迭代)
# 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 not root:return 0
res = 0
stack = [(root, 1)]
while stack:
cur, level = stack.pop()
if not cur.left and not cur.right:
res = max(res, level)
if cur.left:
stack.append((cur.left, level+1))
if cur.right:
stack.append((cur.right, level+1))
return res