R6-二叉树篇

最简单的方法:
循环len(root)次,每次循环执行以下操作:
循环pow(2,i)次,每次都root.pop(0)
如果为空,立即退出,返回i+1
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
root=list(root)
n=len(root)
for i in range(n):
for _ in range(pow(2,i)):
if not root:
return i+1
root=root.pop(0)
一开始就错啦。数类型无法转换为列表,更别谈计算长度。
利用递归:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left=self.maxDepth(root.left)
right=self.maxDepth(root.right)
#1代表当前层
return max(left,right)+1



![[NeurIPS 2024] Self-Refine: Iterative Refinement with Self-Feedback](https://i-blog.csdnimg.cn/direct/f82aaf029cb840f49bd520e185499194.png#pic_center)
















