Convert a binary tree to a Complete Binary Tree

Source: Internet
Author: User

The meaning is to convert a common binary tree into a Complete Binary Tree. The binary tree is stored by link, and the Complete Binary Tree is stored in sequence. The idea is to allocate space to the null node and assign its data field to '#'; the pointer field is null. Sequence traversal of this binary tree

Reference code:

#include<iostream>using namespace std;struct BiNode{char data;BiNode *lchild,*rchild;};char a[200];int flag,len,k;class BiTree{private:BiNode* root;BiNode* Creat(BiNode *bt){char ch;cin>>ch;if(ch=='#'){bt=NULL;}else{len++;flag=1;bt=new BiNode;bt->data=ch;bt->lchild=Creat(bt->lchild);bt->rchild=Creat(bt->rchild);}return bt;}void Release(BiNode *bt){if(bt!=NULL){Release(bt->lchild);Release(bt->rchild);delete bt;}}public:BiTree(){root=Creat(root);}void LeverOrder(){int front,rear;front=rear=-1;BiNode *S[100],*q;if(root==NULL)return;S[++rear]=root;while(front!=rear){q=S[++front];cout<<q->data;if(q->data!='#')k++;if(len==k)break;if(q->lchild!=NULL)S[++rear]=q->lchild;else{BiNode *r=new BiNode;r->data='#';r->lchild=NULL;r->rchild=NULL;S[++rear]=r;}if(q->rchild!=NULL)S[++rear]=q->rchild;else{BiNode *t=new BiNode;t->data='#';t->lchild=NULL;t->rchild=NULL;S[++rear]=t;}}cout<<endl;}~BiTree(){Release(root);}};int main(){int T;cin>>T;while(T--){flag=len=k=0;BiTree A;if(flag==0){cout<<'#'<<endl;continue;}A.LeverOrder();}return 0;}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.