104.二叉树的最大深度
前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)
根节点的高度就是二叉树的最大深度。真正求解深度应该使用高度,即后序遍历。
中序遍历和后序遍历的不同之处在于根节点的访问位置不同,看递归的返回值返回给哪一个值。
递归法
按照中左右的顺序找到树的最大深度,注意递归函数体的写法。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
def depthfunc(node):
if not node:
return 0
leftdepth = depthfunc(node.left) + 1
rightdepth = depthfunc(node.right) + 1
depth = max(leftdepth,rightdepth)
return depth
return depthfunc(root)
111.二叉树的最小深度
最小深度: 根节点到叶子结点的最小距离为最小深度。
前序遍历是求深度的过程,但是本题使用后序代码更简便。
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
def getDepth(node):
if not node:
return 0
leftdepth = getDepth(node.left) # 左
rightdepth = getDepth(node.right) # 右
# 在求最小深度的过程中,需要注意为0的情况,和求最大深度不同点在于需要对左右子树的高度是否为0进行判断
if not node.left and node.right:
depth = 1 + rightdepth # 中
elif not node.right and node.left:
depth = 1 + leftdepth # 中
elif node.left and node.right:
depth = 1 + min(leftdepth,rightdepth) # 中
else:
depth = 1 # 中
return depth
return getDepth(root)
222.完全二叉树的结点个数
利用左右中的顺序进行遍历,将左右孩子的节点数返回给父节点。
在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1) 个节点。
满二叉树:在完全二叉树的基础上判断最左和最右的结点数量是否相等即可。
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
def getNum(node):
if not node:
return 0
leftNum = getNum(node.left)
rightNum = getNum(node.right)
num = leftNum + rightNum + 1
return num
return getNum(root)