数据结构与算法问题 二叉树

#include <cassert>
#include <cmath>
#include <iostream>
#include <queue>
using namespace std;
 
class Node{
public:
    //值
    int data;
    //左孩子
    Node* leftCh;
    //右孩子
    Node* rightCh;
    //所在层
    int level;
    Node(int data, Node* leftCh, Node* rightCh,int level) {
        this->data = data;
        this->leftCh = leftCh;
        this->rightCh = rightCh;
        this->level=level;
    }
};
int*  array;
int n;
/***先序建树
 * */
Node* buildNode(int index,int level){
    if(index>=n){
        return NULL;
    }else{
        Node* p=new Node(array[index], NULL, NULL,level);
        //递归左子树
        p->leftCh=buildNode((index<<1)+1,level+1);
        //递归右子树
        p->rightCh=buildNode((index<<1)+2,level+1);
        return p;
    }
}
 void buildTree(int height){
    n=(int)pow(2, height)-1;
    array=new int[n];
    for(int i=0;i<n;i++){
        array[i]=i+1;
    }
    Node* root=buildNode(0,1);
    queue <Node*> que;
    que.push(root);
    int index=0;
    int level=1;
    //层序输出
    while(!que.empty()){
        Node* p=que.front();
        que.pop();
        //断言顺序表、二叉链表对应的节点相等
        assert(p->data==array[index]);
        if(p->level>level){
                    cout<<endl;
                    level++;
                }
        cout<<p->data<<" ";
        index++;
        if(p->leftCh!=NULL){
            que.push(p->leftCh);
        }
        if(p->rightCh!=NULL){
            que.push(p->rightCh);
        }
    }
    cout<<endl;
}
 
 
 
int main(int argc, char **argv) {
    buildTree(4);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值