#include<iostream> #include<vector> using namespace std; struct Node { char value; Node *left; Node *right; }; void create(Node *&T) { char c; cin>>c; if('#'==c) { T=NULL; } else { T=new Node; T->value=c; create(T->left); create(T->right); } } void preorder(Node *node) { if(node==NULL) return; else { cout<<node->value<<" "; preorder(node->left); preorder(node->right); } } void printnodebylevel(Node *root) { if(root==NULL) return ; vector<Node *> vec; vec.push_back(root); int cur=0; int last=1; while(cur<vec.size()) { last=vec.size(); while(cur<last) { cout<<vec[cur]->value<<" "; if(vec[cur]->left!=NULL) vec.push_back(vec[cur]->left); if(vec[cur]->right!=NULL) vec.push_back(vec[cur]->right); cur++; } cout<<endl; } } int main() { Node *root; create(root); //preorder(root); //cout<<endl; printnodebylevel(root); system("pause"); return 0; }
时间: 2024-10-09 13:17:07