104.二叉树的最大深度 (优先掌握递归)
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解: 代码随想录
解题思路:
递归思路左右中 先递归左的 在递归右的高度 当前中的高度为1+leftheight和rightheight中大的数。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
left=self.maxDepth(root.left)
right=self.maxDepth(root.right)
height=1+max(left,right)
return height
111.二叉树的最小深度 (优先掌握递归)
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
和最大深度差不多
递归思路左右中 先递归左的 再递归右的高度
如果左子树为空右子树不为空的话 注意不能return当前中的高度为1+leftheight和rightheight中小的数 要return 1+右子树的高度 因为题目要求root到leaf的距离。
同理 当右子树为空左子树不为空的话 return 1+左子树的高度。
如果左右都不为空 就return1+leftheight和rightheight中小的数
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left is None and root.right is None:
return 1
leftheight = self.minDepth(root.left)
rightheight = self.minDepth(root.right)
if root.left == None and root.right !=None:
return 1 + rightheight
if root.right == None and root.left != None:
return 1 + leftheight
return 1 + min(leftheight,rightheight)
222.完全二叉树的节点个数(优先掌握递归)
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
左右中 递归数左子树 递归数右子树 最后结合左右子树再加1(中)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
leftcount=self.countNodes(root.left)
rightcount=self.countNodes(root.right)
return 1+leftcount+rightcount
文章讲述了如何使用递归方法解决二叉树的最大深度、最小深度问题,以及计算完全二叉树的节点数量。在LeetCode平台上,这些问题被重点推荐使用递归思路解决,代码随想录提供了相关题目的链接和解题策略。

被折叠的 条评论
为什么被折叠?



