#includeusing namespace std; struct Bstnode { char data; Bstnode* left; Bstnode* right; }; //创建新节点 Bstnode* GetNewNode(int data) { Bstnode* newNode = new Bstnode(); (*newNode).data = data; newNode->left = newNode->right = NULL; return newNode; } //插入元素 Bstnode* Insert(Bstnode* root, int data) { if (root == NULL) { root = GetNewNode(data); } else if (data <= root->data) { root->left = Insert(root->left, data); } else { root->right = Insert(root->right, data); } return root; } //层次遍历 void LevelOrder(Bstnode* root) { if (root == NULL) return; queue Q; Q. push(root); while (!Q.empty()) { Bstnode* current = Q.front(); cout << current->data << " "; if (current->left != NULL) Q.push(current->left); if (current->right != NULL) Q.push(current->right); Q.pop(); } } //前序遍历 void Preorder(Bstnode* root) { if (root == NULL) return; cout << root->data <<" "; Preorder(root->left); Preorder(root->right); } //中序遍历 void Inorder(Bstnode* root) { if (root == NULL) return; Inorder(root->left); cout << root->data << " "; Inorder(root->right); } //后序遍历 void Postorder(Bstnode* root) { if (root == NULL) return; Postorder(root->left); Postorder(root->right); cout << root->data << " "; } int main() { Bstnode* root=NULL; root = Insert(root, 'F');root = Insert(root, 'D');root = Insert(root, 'J'); root = Insert(root, 'B');root = Insert(root, 'E');root = Insert(root, 'G'); root = Insert(root, 'K');root = Insert(root, 'A'); root = Insert(root, 'C'); root = Insert(root, 'I'); LevelOrder(root); cout << endl; Preorder(root); cout << endl; Inorder(root); cout << endl; Postorder(root); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)