目录
104.二叉树的最大深度
什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。大家 要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。
题目链接/文章讲解/视频讲解: 代码随想录
思路
深度和高度是不一样的,深度是从上面的根节点往下数,高度是从下面叶子节点往上数,所以分别适合采用前序遍历和后序遍历。
代码
class Solution:
def maxdepth(self, root: 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) #右
height = 1 + max(leftheight, rightheight) #中
return height
111.二叉树的最小深度
先看视频讲解,和最大深度 看似差不多,其实 差距还挺大,有坑。题目链接/文章讲解/视频讲解:代码随想录
思路
只有左右节点都是空才到达了最下层。采用因为是求深度,所以采用前序遍历。
代码
class Solution:
def getDepth(self, node):
if node is None:
return 0
leftDepth = self.getDepth(node.left) # 左
rightDepth = self.getDepth(node.right) # 右
# 当一个左子树为空,右不为空,这时并不是最低点
if node.left is None and node.right is not None:
return 1 + rightDepth
# 当一个右子树为空,左不为空,这时并不是最低点
if node.left is not None and node.right is None:
return 1 + leftDepth
result = 1 + min(leftDepth, rightDepth)
return result
def minDepth(self, root):
return self.getDepth(root)
222.完全二叉树的节点个数
需要了解,普通二叉树 怎么求,完全二叉树又怎么求题目链接/文章讲解/视频讲解:代码随想录
思路
要充分利用完全二叉树的性质,概念不牢,地动山摇。 先判断最左边和最右边是不是一样深度,一样直接按满二叉树算,不一样就一直递归下去。
代码
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
left = root.left
right = root.right
leftDepth = 0 #这里初始为0是有目的的,为了下面求指数方便
rightDepth = 0
while left: #求左子树深度
left = left.left
leftDepth += 1
while right: #求右子树深度
right = right.right
rightDepth += 1
if leftDepth == rightDepth:
return (2 << leftDepth) - 1 #注意(2<<1) 相当于2^2,所以leftDepth初始为0
return self.countNodes(root.left) + self.countNodes(root.right) + 1