leetcode104.二叉树的最大深度
题目链接:104. 二叉树的最大深度 - 力扣(LeetCode)
视频讲解:二叉树的高度和深度有啥区别?究竟用什么遍历顺序?很多录友搞不懂 | LeetCode:104.二叉树的最大深度_哔哩哔哩_bilibili
思路:递归法,二叉树的深度就是二叉树任意一个节点到根节点的距离,用前序排列算,二叉树的高度是二叉树任意一个,节点到叶结点的距离,用后序排列算,根节点的高度就是二叉树的最大深度 ,所以可以用后序排列
# 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:
return self.getdepth(root)
def getdepth(self, node):
if not node:
return 0
leftdepth = self.getdepth(node.left)
rightdepth = self.getdepth(node.right)
depth = 1 + max(leftdepth, rightdepth)
return depth
leetcode111.二叉树的最小深度
题目链接:111. 二叉树的最小深度 - 力扣(LeetCode)
思路:前面跟二叉树最大深度一样写个函数获取左子树,右子树的长度,本提规定最小深度不包括root没有分支的情况,所以求完左右子树长度后不能直接取最小,要是root.left是None但root.roght不是,就取右边的长度,反之取左边的长度。最后再返回左右长度的最小值。
# 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 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: Optional[TreeNode]) -> int:
return self.getDepth(root)
222.完全二叉树的节点个数
题目链接: 222. 完全二叉树的节点个数 - 力扣(LeetCode)
视频讲解:要理解普通二叉树和完全二叉树的区别! | LeetCode:222.完全二叉树节点的数量_哔哩哔哩_bilibili
思路:递归法跟前两个题目很像,写一个函数先获取左子树节点,再获取右子树节点,再加起来,这是把它当作普通二叉树的处理方法
# 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 getCountNodes(self, node):
if node is None:
return 0
leftcountnode = self.getCountNodes(node.left)
rightcountnode = self.getCountNodes(node.right)
result = leftcountnode + rightcountnode + 1
return result
def countNodes(self, root: Optional[TreeNode]) -> int:
return self.getCountNodes(root)