Implement the serializeTreeNodeCount method that returns the number of nodes represented during tree serialization.

The input contains a binary tree represented as an integer array tree and its length size.

Your task is to return how many actual tree nodes are present. In this problem set, missing nodes are represented by 0, so they should not be counted.

For example, [1,2,3,0,0,4,5] has five actual nodes: 1,2,3,4,5.

Example 1

Input
tree (int[]) = [1,2,3,0,0,4,5]
size (int) = 7
Returns (int) 5

Example 2

Input
tree (int[]) = []
size (int) = 0
Returns (int) 0

Example 3

Input
tree (int[]) = [1,0,2]
size (int) = 3
Returns (int) 2

Scan the tree array and count only values that represent real nodes.

Whenever a value is not the missing-node marker, increase the count. Values marked as missing should be skipped because they do not represent tree nodes in the serialized form.

After scanning all positions, return the count.

Pseudocode:

function serializeTreeNodeCount(tree, size):
    count = 0
    for i from 0 to size - 1:
        if tree[i] is not missing:
            count++
    return count
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.