104.二叉树的最大深度 (优先掌握递归)
什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。
大家 要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。
题目链接/文章讲解/视频讲解: https://programmercarl.com/0104.二叉树的最大深度.html
# 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
return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1
111.二叉树的最小深度 (优先掌握递归)
先看视频讲解,和最大深度 看似差不多,其实 差距还挺大,有坑。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0111.二叉树的最小深度.html
思考
左节点和右节点同时为空,才到达叶子节点。注意看下面这种情况。
# 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
if root.left is None and root.right is not None:
return self.minDepth(root.right)+1
elif root.right is None and root.left is not None:
return self.minDepth(root.left)+1
else:
return min(self.minDepth(root.left),self.minDepth(root.right))+1
222.完全二叉树的节点个数
需要了解,普通二叉树 怎么求,完全二叉树又怎么求
题目链接/文章讲解/视频讲解:https://programmercarl.com/0222.完全二叉树的节点个数.html
思考
递归版本,适合所有二叉树
# 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
return 1 + self.countNodes(root.left)+self.countNodes(root.right)
利用完全二叉树的性质,用公式来计算满二叉树的节点个数。
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
# 剪枝,利用完全二叉树性质,如果是满二叉树,直接用深度求节点数
left = root.left
right = root.right
left_depth = 0
right_depth = 0
while left:
left = left.left
left_depth+=1
while right:
right = right.right
right_depth+=1
if left_depth == right_depth:
#print(left_depth)
return 2**(left_depth+1) -1
return 1 + self.countNodes(root.left)+self.countNodes(root.right)
标签:None,right,self,Day16,二叉树,深度,root,left
From: https://www.cnblogs.com/forrestr/p/18237868