题目描述:
题目思路:
1.用结构链表来建树
2.用队列来实现层次遍历,当遍历到根节点时,将其子节点压入队列
#include <iostream> #include <cstdlib> #include <cstring> #include <vector> #include <queue> using namespace std; //树结点 struct Node{ int v ; Node* left,*right ; int have_value ; Node():have_value(false),left(NULL),right(NULL){} ; } ; Node* root ;//根节点 Node* newnode(){ return new Node() ; //返回一个新结点 } bool failed ; void addnode(int v,char* s){//添加新结点 int n = strlen(s); Node* u = root ; for(int i = 0;i < n;i++)//找到要加入的位置 { if(s[i] == ‘L‘){ if(u->left == NULL) u->left = newnode(); u = u->left; } else if(s[i] == ‘R‘){ if(u->right == NULL) u->right= newnode(); u = u->right ; } } if(u->have_value) failed = true ;//是否已经被访问过; u->v = v; u->have_value = true; } void freetree(Node* u){ //释放内存 if(u == NULL) return ; freetree(u->left); freetree(u->right); delete u; } char s[1005]; bool read_input(){ failed = false ; freetree(root) ; root = newnode(); while(true){ if(scanf("%s", s) != 1) return false; if(!strcmp(s,"()")) break; int v ; sscanf(&s[1],"%d",&v); addnode(v,strchr(s,‘,‘)+1); } return true ; } bool bfs(vector<int>& ans){//搜索 queue<Node*> q; ans.clear(); q.push(root); while(!q.empty()){ Node *u = q.front();q.pop(); if(!u->have_value) return false; ans.push_back(u->v); if(u->left != NULL) q.push(u->left); if(u->right != NULL) q.push(u->right); } return true ; } int main(int argc, char *argv[]) { vector<int> ans; while(read_input()){ if(!bfs(ans)) failed = 1; if(failed) printf("not complete\n"); else{ for(int i = 0;i < ans.size();i++) { if(i != 0) cout << " " ; cout << ans[i]; } cout << endl ; } } return 0; }
原文地址:https://www.cnblogs.com/secoding/p/9532537.html
时间: 2024-10-08 13:46:46