104.二叉树的最大深度
运用了层序遍历
# 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
depth=0
queue=collections.deque([root])
while queue:
depth+=1
for _ in range(len(queue)):
node=queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
使用后续遍历
# 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:
return self.getdepth(root)
def getdepth(self,node):
if not node:
return 0
left_height=self.getdepth(node.left)
right_height=self.getdepth(node.right)
height=1+max(left_height,right_height)
return height
本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
而根节点的高度就是二叉树的最大深度,所以本题中我们通过后序求的根节点高度来求的二叉树最大深度。
111.二叉树的最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。,注意是叶子节点。
迭代法:只有当左右孩子都为空的时候,才说明遍历到最低点了。如果其中一个孩子不为空则不是最低点
迭代法
# 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 minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
depth=0
queue=collections.deque([root])
while queue:
depth+=1
for _ in range(len(queue)):
node=queue.popleft()
if not node.left and not node.right:
return depth
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
递归法,后续
# 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 minDepth(self, root: Optional[TreeNode]) -> int:
return self.getDepth(root)
def getDepth(self,node):
if node is None:
return 0
leftDepth=self.getDepth(node.left)#左
rightDepth=self.getDepth(node.right)
if node.left is None and node.right is not None:#左空右不空,此时并不是最低点,继续向下
return 1+rightDepth
if node.left is not None and node.right is None:
return 1+leftDepth
result=1+min(leftDepth,rightDepth)
return result
前序
# 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 __init__(self):
self.result=float('inf')#定义最小值为最大
def minDepth(self, root: Optional[TreeNode]) -> int:
return self.getDepth(root,1)
def getDepth(self,node,depth):
if node is None:
return 0
if node.left is None and node.right is None:
self.result=min(self.result,depth)
if node.left:
self.getDepth(node.left,depth+1)
if node.right:
self.getDepth(node.right,depth+1)
return self.result