104. 二叉树最大深度
广度优先遍历(层序遍历):
#### 层序遍历 ####
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
result = 0
if not root:
return result
from collections import deque
_list = deque()
_list.append(root)
while(_list):
for _ in range(len(_list)):
node = _list.popleft()
if node.left:
_list.append(node.left)
if node.right:
_list.append(node.right)
result += 1
return result
后序遍历
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def get_height(node):
if not node:
return 0
left_height = get_height(node.left) #左
right_height = get_height(node.right) #右
height = 1 + max(left_height, right_height) #中
return height
return get_height(root)
111. 最小深度
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
def get_height(node):
if not node:
return 0
left_height = get_height(node.left)
right_height = get_height(node.right)
if not node.left and node.right:
height = 1 + right_height
elif node.left and not node.right:
height = 1 + left_height
else:
height = 1 + min(left_height, right_height)
return height
return get_height(root)
和最大深度差别在于处理的方式,碰到空的情况不能算深度
222. 完全二叉树节点个数
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
leftNum = self.countNodes(root.left)
rightNum = self.countNodes(root.right)
Num = leftNum + rightNum + 1
return Num
递归还是得想想