Title Description
Binary tree can be stored by array method. The data in the array can be stored from top to bottom, from left to right in the node of the binary tree. Compared with the complete binary tree, the node that is missing from the complete binary tree is represented by 0 in the array. As shown in the following figure
As can be seen from the figure above, a common binary tree is on the right. When it is compared with the complete binary tree on the left, it is found that it has fewer Nos. 5 than the complete binary tree. So it is represented by 0 in the array, and it also has fewer Nos. 10 and 11 in the complete binary tree, so it is also represented by 0 in the array.
The data stored in nodes are all non-negative integers
Enter the first line and enter an integer t to indicate that there are t binary trees.
From the second line, an array is input in each line. First, the length of the array is input, then the data in the array is input. Each data is separated by spaces, and the input data is non-negative integers.
Continuous input t line
Output each line to output a precedence traversal result of an example, separated by spaces between each node
sample input
3
3 1 2 3
5 1 2 3 0 4
13 1 2 3 4 0 5 6 7 8 0 0 9 10
sample output
1 2 3
1 2 4 3 1 2 4 7 8 3 5 9 10 6
thinking
#include<iostream> #include<string> #include<stack> using namespace std; const int maxx= 1e4; int main(){ int t; cin>>t; while(t--){ int n; int *array; cin>>n; array= new int[maxx]; int flag= 0; for(int i= 1; i<= n; i++){ cin>>array[i]; if(array[i]) flag++;//Number of Nodes Recorded } int pos = 1; stack<int> st; cout<<array[1]<<' '; int k= 0; while(k!= flag- 1){ if(array[pos*2]&&array[pos*2+ 1]){ st.push(pos*2 + 1); cout<<array[pos*2]<<' '; k++; pos= pos*2; } if(array[pos*2]&&!array[pos* 2+ 1]){ cout<<array[pos*2]<<' '; k++; pos= pos*2; } if(!array[pos*2]&&array[pos*2+ 1]){ cout<<array[pos*2+ 1]<<' '; k++; pos= pos*2+ 1; } if(!array[pos*2]&&!array[pos*2+ 1]){ if(!st.empty()){ pos= st.top(); cout<<array[pos]<<' '; k++; st.pop(); } } } cout<<endl; delete []array; } }