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