I am working on a C++ code to find out the number of leave node in a binary tree using array input my code is:
int leaf(int data[],int size) {
int result = 0;
for (int i = 0; i <= size; i++) {
if (data[i] == -1)
i++;
if (((data[(2*i)+1] == -1) && (data[(2 * i) +2] == -1)) || ((data[(2 * i) +1] == NULL) && (data[(2 * i) +2] == NULL)))
result++;
}
return result;
}
int main(){
int data[]= { 1,9, 6, 8 ,12, 2,-1 ,10, -1 ,-1 ,-1, 5 };
int size = 12;
cout << "count of leave node: " << leaf(data, size)<< endl;
}
In the array, the element -1 is the empty node.
The tree is like:
1
/ \
9 6
/ \ /
8 12 2
/ /
10 5
The total number of the leave node should be 3 which is (12,10,5), but the result of my code is 2. Can I know what wrong with my code and how to fix it. Big Thanks!