# 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 = rightclassSolution:defmaxDepth(self, root: Optional[TreeNode])->int:ifnot root:return0
deep =1
queue =[(root,deep)]while queue:
node,deep = queue.pop(0)if node.left:
queue.append((node.left,deep+1))if node.right:
queue.append((node.right,deep+1))return deep
递归-DFS思路
# 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 = rightclassSolution:defmaxDepth(self, root: Optional[TreeNode])->int:ifnot root:return0
leftHeight = self.maxDepth(root.left)
rightHeight = self.maxDepth(root.right)returnmax(leftHeight,rightHeight)+1
559.n叉树的最大深度
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""classSolution:defmaxDepth(self, root:'Node')->int:# 若当前节点为空则deep为0ifnot root:return0# 若当前节点没有child 则deep =1ifnot root.children:return1returnmax(self.maxDepth(node)+1for node in root.children)
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""classSolution:defmaxDepth(self, root:'Node')->int:
queue =[]
queue.append(root)
level =0ifnot root:return0while queue:# 该层的节点数量
queueLen =len(queue)
level+=1for i inrange(queueLen):
node = queue.pop(0)# 如果当前节点依然有孩子节点 则把他的孩子节点也加到队列中if node.children andlen(node.children)>0:for item in node.children:
queue.append(item)return level
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 = rightclassSolution:defminDepth(self, root: Optional[TreeNode])->int:ifnot root:return0ifnot root.left ornot root.right:return1
leftHeight = self.minDepth(root.left)
rightHeight = self.minDepth(root.right)returnmin(leftHeight,rightHeight)+1