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 root is None:
return 0
else:
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return 1 + max(left, right)
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 root is None:
return 0
else:
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if root.left and root.right:
return 1+min(left, right)
elif root.left is None and root.right:
return 1+right
elif root.right is None and root.left:
return 1+left
else:
return 1
222.完全二叉树的节点个数
# 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 countNodes(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
else:
left = self.countNodes(root.left)
right = self.countNodes(root.right)
return 1+left+right
标签:None,right,self,随想录,二叉树,深度,root,left
From: https://www.cnblogs.com/miramira/p/18117499