📅  最后修改于: 2023-12-03 15:40:25.340000             🧑  作者: Mango
在二叉树中,每个非叶子节点都有两个子节点,而叶子节点没有子节点。正确的叶子节点是指落在树上的叶子节点,同时其所在的层数是整棵树的最大层数。
本文将介绍如何查找二叉树中所有正确叶子的总和,并给出相应的代码实现。
要查找二叉树中所有正确叶子的总和,我们需要遍历整棵树,同时记录每个叶子节点所在的层数。如果一个节点是叶子节点,并且其所在的层数是整棵树的最大层数,那么就把它的值累加到总和中。
在遍历过程中,可以使用递归或迭代的方式访问树中的每个节点。对于每个节点,我们都需要计算它所在的层数并进行比较。如果它是叶子节点并且满足条件,则将其值累加到总和中。
以下是使用递归遍历的代码实现:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def get_max_depth(root):
if root is None:
return 0
return max(get_max_depth(root.left), get_max_depth(root.right)) + 1
def sum_of_right_leaves(root):
max_depth = get_max_depth(root)
res = 0
def dfs(node, depth):
nonlocal res
if node is None:
return
if node.left is None and node.right is None and depth == max_depth:
res += node.val
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root, 1)
return res
如果不想使用递归,也可以使用迭代的方式实现。以下是迭代遍历的代码实现:
def sum_of_right_leaves(root):
max_depth = get_max_depth(root)
res = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
if node is None:
continue
if node.left is None and node.right is None and depth == max_depth:
res += node.val
stack.append((node.right, depth + 1))
stack.append((node.left, depth + 1))
return res
本文介绍了如何查找二叉树中所有正确叶子的总和。我们可以使用递归或迭代的方式遍历整棵树,并记录每个叶子节点所在的层数。最后,只需累加那些满足条件的叶子节点的值即可。