void Preorder(node* root){ if(root==NULL){ return ; } cout<<root->data<<" "; Preorder(root->lchild); //递归 Preorder(root->rchild); } void Inorder(node* root){ if(root==NULL){ return ; } Inorder(root->lchild); cout<<root->data<<" "; Inorder(root->rchild); } void Postorder(node* root){ if(root==NULL){ return ; } Postorder(root->lchild); Postorder(root->rchild); cout<<root->data<<" "; } void Lorder(node* root){ //层序相当于BFS queue<node*> q; q.empalce(root); while(!q.empty()){ node* n=q.front(); q.pop(); cout<<n->data<<" "; if(n->lchild!=NULL){ q.emplace(n->lchild); } if(n->rchild!=NULL){ q.emplace(n->rchild); } } return ; } struct node{ int data,layer; node* lchild; node* rchild; }; void Lorder2(node* root){ queue<node*> q; root->layer=1; q.emplace(root); while(!q.empty()){ node* n=q.front(); q.pop(); cout<<n->data<<" "; if(!n->lchild){ n->lchild.layer=n.layer+1; q.emplace(n->lchild); } if(!n->rchild){ n->rchild.layer=n.layer+1; q.emplace(n->rchild); } } return ; }
12-20
2708
03-14
1003