Sum of Leaf Nodes in a Binary Tree
Trees are fundamental data structures widely used in computer science to represent hierarchical relationships. Understanding how to traverse and manipulate trees is crucial for solving many algorithmic problems, from file system navigation to parsing expressions. This problem focuses on identifying and aggregating specific nodes within a binary tree, laying a foundation for more complex tree-based data processing.
Implement a function that calculates the sum of all leaf nodes in a given binary tree. A leaf node is defined as a node that has no children (i.e., both its left and right child pointers are null).
Your function should have the following signature:
function sumLeafNodes(root: TreeNode | null): number
root: The root node of the binary tree. It will be null if the tree is empty.node.left and node.right are null.val) can be positive, negative, or zero.root is null, it signifies an empty tree.Examples
Example 1
Input:
root = [3,9,20,null,null,15,7]
Output:
31
Note:
The leaf nodes are 9, 15, and 7. Their sum is 9 + 15 + 7 = 31.
Example 2
Input:
root = [1]
Output:
1
Note:
The root node itself is a leaf node as it has no children. Its value is 1.
Example 3
Input:
root = null
Output:
0
Note:
The tree is empty, so there are no leaf nodes. The sum is 0.
Constraints
Node.val is an integer between -1000 and 1000.TreeNode structure (assume valid tree nodes).Loading editor...