只先写了递归,迭代暂时没写
104.二叉树的最大深度
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left),self.maxDepth(root.right))
111.二叉树的最小深度
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
elif root.left and not root.right:
return 1+ self.minDepth(root.left)
elif root.right and not root.left:
return 1+ self.minDepth(root.right)
return 1+min(self.minDepth(root.left),self.minDepth(root.right))
222.完全二叉树的节点个数
–普通二叉树的节点数 AND 完全二叉树节点数
# 普通二叉树
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1+self.countNodes(root.left)+self.countNodes(root.right)
## 完全二叉树--记住思路
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
leftNum,rightNum = 0,0
cur = root.left
while cur:
cur = cur.left
leftNum += 1
cur = root.right
while cur:
cur = cur.right
rightNum += 1
if leftNum == rightNum:
return (2<<leftNum)-1
return 1 + self.countNodes(root.left) + self.countNodes(root.right)