user1225752
user1225752

Reputation: 75

Populate the data field of all the nodes of the tree

A node of a binary tree has two pointers, 'left' and 'right', and two data fields, 'leftcount' and 'rightcount'. 'leftcount' specifies the number of nodes in the left subtree of the node, and 'rightcount' specifies the number of nodes in the right subtree of the node. Write an algorithm to populate the data fields of all the nodes of the tree.

I was asked this question in an interview. I came up with a solution which was based on a postorder traversal of the tree. Can someone please guide me on this.

Upvotes: 0

Views: 199

Answers (1)

Lior
Lior

Reputation: 171

This should work (I believe):

int populateCounters(Node* node) {
    if(node == NULL) return 0;
    node->leftCount = populateCounters(node->left);
    node->rightCount = populateCounters(node->right);
    return node->leftCount + node->rightCount + 1;
}

Upvotes: 1

Related Questions