You are given the root of a binary tree, root. Return the sum of the values of every leaf that is a right child.
A leaf is a node with no children. The root is never a right child, even when it has no children itself, so the root never counts.
Return 0 if there are no right leaves.
Tree Encoding
Your function receives root as a TreeNode. The node type is provided for you, with val, left, and right fields.
The examples below write the tree as its level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how the input is displayed; the decoding is done for you.
Constraints
The number of nodes in root is in the range [1,105].
−104≤Node.val≤104
Examples
Example 1
Input
root = [3, 9, 20, null, null, 15, 7]
root
Output
7
Explanation
Only `7` is a leaf that is a right child (the right child of `20`); `9` is a left leaf and `15` is a left leaf, so neither counts. The answer is `7`.
Example 2
Input
root = [1, 2, 3, 4, 5]
root
Output
8
Explanation
`3` is a right leaf (the right child of the root) and `5` is a right leaf (the right child of `2`); `4` is a left leaf, so it does not count. The answer is `3 + 5 = 8`.
Example 3
Input
root = [1]
root
Output
0
Explanation
The single node `1` has no right child at all, so there are no right leaves and the answer is `0`.
Loading editor...
Run checks the sample cases; Submit runs every case.
Samples 3
Custom 0
passedwrong answertime limiterrorran, no expected valuenot run