104.二叉树的最大深度
本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
根节点的高度就是二叉树的最大深度,所以本题可以通过后序求根节点高度来求的二叉树最大深度。
前序遍历,求深度
result作为参数时无法传递回来,必须将result作为一个全局变量
class Solution:def __init__(self):self.result = 0def maxDepth(self, root: Optional[TreeNode]) -> int:self.depth(root, 0)return self.resultdef depth(self, cur, depth):if not cur:returnself.result = max(self.result, depth + 1)self.depth(cur.left, depth + 1)self.depth(cur.right, depth + 1)
后序遍历,求根节点的高度
class Solution:def maxDepth(self, root: Optional[TreeNode]) -> int:if not root:return 0left_depth = self.maxDepth(root.left)right_depth = self.maxDepth(root.right)return max(left_depth, right_depth) + 1
111.二叉树的最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。注意是叶子节点。
使用后序遍历,其实求的是根节点到叶子节点的最小距离,就是求高度的过程,不过这个最小距离 也同样是最小深度。
class Solution:def minDepth(self, root: Optional[TreeNode]) -> int:if not root:return 0left_depth = self.minDepth(root.left)right_depth = self.minDepth(root.right)# 针对非叶子节点进行限制if not root.left and root.right:return 1 + right_depthif not root.right and root.left:return 1 + left_depthreturn 1 + min(left_depth, right_depth)
222.完全二叉树的节点个数
遍历完全二叉树一次即可以求出节点个数
class Solution:def countNodes(self, root: Optional[TreeNode]) -> int:if not root:return 0return 1 + self.countNodes(root.left) + self.countNodes(root.right)
但是完全二叉树有自己的特性,可以将完全二叉树划分为小的满二叉树,当是小的满二叉树时,可以利用公式
class Solution:def countNodes(self, root: Optional[TreeNode]) -> int:if not root:return 0left = root.leftright = root.rightleft_depth = 0right_depth = 0while left:left = left.leftleft_depth += 1while right:right = right.rightright_depth += 1if left_depth == right_depth:# return 2 ** (left_depth+1) - 1return (2 << left_depth) - 1return self.countNodes(root.left) + self.countNodes(root.right) + 1