DS二叉树——二叉树之数组存储

版权声明:转载请注明出处 https://blog.csdn.net/weixin_41879093/article/details/83096004

题目描述
二叉树可以采用数组的方法进行存储,把数组中的数据依次自上而下,自左至右存储到二叉树结点中,一般二叉树与完全二叉树对比,比完全二叉树缺少的结点就在数组中用0来表示。,如下图所示

从上图可以看出,右边的是一颗普通的二叉树,当它与左边的完全二叉树对比,发现它比完全二叉树少了第5号结点,所以在数组中用0表示,同样它还少了完全二叉树中的第10、11号结点,所以在数组中也用0表示。

结点存储的数据均为非负整数

输入 第一行输入一个整数t,表示有t个二叉树

第二行起,每行输入一个数组,先输入数组长度,再输入数组内数据,每个数据之间用空格隔开,输入的数据都是非负整数

连续输入t行

输出 每行输出一个示例的先序遍历结果,每个结点之间用空格隔开

样例输入
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
样例输出
1 2 3
1 2 4 3 1 2 4 7 8 3 5 9 10 6

思路

#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++;//记录数的节点数
        }
            

               
        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;
    }
}

递归算法如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41879093/article/details/83096004