代码随想录 - Day23 - 二叉树最大深度&最小深度
class Solution :
def maxDepth ( self, root: Optional[ TreeNode] ) - > int :
return self. getDepth( root)
def getDepth ( self, node) :
if not node:
return 0
leftHeight = self. getDepth( node. left)
rightHeight = self. getDepth( node. right)
hight = 1 + max ( leftHeight, rightHeight)
return hight
class Solution :
def maxDepth ( self, root: Optional[ TreeNode] ) - > int :
if not root:
return 0
queue = collections. deque( [ root] )
cnt = 0
while queue:
size = len ( queue)
for _ in range ( size) :
cur = queue. popleft( )
if cur. left:
queue. append( cur. left)
if cur. right:
queue. append( cur. right)
cnt += 1
return cnt
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution :
def maxDepth ( self, root: 'Node' ) - > int :
if not root:
return 0
depth = 1
for child in root. children:
depth = max ( depth, self. maxDepth( child) + 1 )
return depth
class Solution :
def maxDepth ( self, root: 'Node' ) - > int :
if not root:
return 0
queue = collections. deque( [ root] )
depth = 0
while queue:
depth += 1
size = len ( queue)
for _ in range ( len ( queue) ) :
cur = queue. popleft( )
for child in cur. children:
queue. append( child)
return depth
class Solution :
def minDepth ( self, root: Optional[ TreeNode] ) - > int :
return self. getDepth( root)
def getDepth ( self, node) :
if not node:
return 0
leftDepth = self. getDepth( node. left)
rightDepth = self. getDepth( node. right)
if not node. left and node. right:
return 1 + rightDepth
if node. left and not node. right:
return 1 + leftDepth
return 1 + min ( leftDepth, rightDepth)
迭代法:层序遍历,除了根节点,一旦遇到一个没有左节点或右节点的节点,就返回累计的深度
class Solution :
def minDepth ( self, root: Optional[ TreeNode] ) - > int :
if not root:
return 0
queue = collections. deque( [ root] )
cnt = 0
while queue:
size = len ( queue)
cnt += 1
for _ in range ( size) :
cur = queue. popleft( )
if not cur. left and not cur. right:
return cnt
if cur. left:
queue. append( cur. left)
if cur. right:
queue. append( cur. right)
return cnt