print every second leaf node from right to left

let me say that I have tree and the tree has these leaf nodes from right to left:
[ 9, 4, 6,16 ,8,19, 10,8 ], I should write function to print every second leaf node from right to left, so the output should be {4, 16 , 19 ,8 }, and ignore the rest
I wrote function but it prints all leaf nodes!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21




    

void writeEveryOtherLeafNode (Node* node) {
   
   if (node == NULL) {
       return;
   }
   
  
   if (node->left == NULL && node->right == NULL) {
       std::cout << node-> ID << " ";
   }
   
   
   writeEveryOtherLeafNode(node->right);
   writeEveryOtherLeafNode(node->left);
}
The easiest way is probably to pass an additional bool argument by reference to keep track of whether you should print the next leaf or not. Every time you reach a leaf node you flip the bool and check if you should print.

Another alternative is to instead pass a container and instead of printing you just add the leaf node values to the container, and when you have traversed the whole tree you can simply loop over the container and print every other value.
Last edited on
Maybe something like (not tried):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void writeEveryOtherLeafNode(Node* node, bool& disp) {
	if (node)
		if (!node->left && !node->right) {
			if (disp = !disp)
				std::cout << node->ID << " ";
		} else {
			writeEveryOtherLeafNode(node->left, disp);
			writeEveryOtherLeafNode(node->right, disp);
		}
}

void writeEveryOtherLeafNode(Node* node) {
	bool d { true };

	writeEveryOtherLeafNode(node, d);
}

Registered users can post here. Sign in or register to post.