二叉树最大深度
- 给定一个二叉树 root ,返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 示例 1:
二叉树最大深度
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
depth = 0
queue = collections.deque([root])
while queue:
print(len(queue))
level = []
depth += 1
for _ in range(len(queue)):
cur = queue.popleft()
level.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return depth
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
return self.getdepath(root)
def getdepath(self, node):
if not node:
return 0
leftdepath = self.getdepath(node.left)
rightdepath = self.getdepath(node.right)
height = 1 + max(leftdepath, rightdepath)
return height
二叉树最小深度
- 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。
- 示例 1:
二叉树最小深度
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
depth = 0
queue = collections.deque([root])
while queue:
level = []
depth += 1
for _ in range(len(queue)):
cur = queue.popleft()
if not cur.left and not cur.right:
return depth
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return depth