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