// #define NORM_BINARY_TREE #define THREAD_BINARY_TREE #include #include using namespace std; #pragma region BinaryTree template class BinaryTree { public: // 左、右孩子结点对应的指针 BinaryTree *leftChild = nullptr; BinaryTree *rightChild = nullptr; // 当前结点存放的值 T value; BinaryTree(T nodeValue); }; template BinaryTree::BinaryTree(T nodeValue) { value = nodeValue; } template BinaryTree *createBinaryTreeNode(T nodeValue) { return new BinaryTree(nodeValue); } #pragma endregion #pragma region Functions template void preOrder(BinaryTree *tree) { if (tree != nullptr) { cout << "[" << tree->value << "] " << endl; preOrder(tree->leftChild); preOrder(tree->rightChild); } } template void inOrder(BinaryTree *tree) { if (tree != nullptr) { inOrder(tree->leftChild); cout << "[" << tree->value << "] " << endl; inOrder(tree->rightChild); } } template void postOrder(BinaryTree *tree) { if (tree != nullptr) { postOrder(tree->leftChild); postOrder(tree->rightChild); cout << "[" << tree->value << "] " << endl; } } template void levelOrder(BinaryTree *tree) { // 初始化一个队列 queue *> bTreeQueue; // 将当前节点入队 bTreeQueue.push(tree); // 若队列不为空,则说明这一层还有节点 while (bTreeQueue.size() > 0) { // 出队队首元素,并输出该节点的值 BinaryTree *currentFront = bTreeQueue.front(); bTreeQueue.pop(); cout << "[" << currentFront->value << "] " << endl; if (currentFront->leftChild != nullptr) { // 将左孩子节点入队 bTreeQueue.push(currentFront->leftChild); } if (currentFront->rightChild != nullptr) { // 将右孩子节点入队 bTreeQueue.push(currentFront->rightChild); } } } #pragma endregion int main(int argc, char *argv[]) { // 初始化节点 BinaryTree *root = createBinaryTreeNode(1); BinaryTree *a = createBinaryTreeNode(2); BinaryTree *b = createBinaryTreeNode(3); BinaryTree *d = createBinaryTreeNode(4); BinaryTree *e = createBinaryTreeNode(5); BinaryTree *f = createBinaryTreeNode(6); // 为不同节点指定左、右孩子节点 root->leftChild = a; root->rightChild = b; a->leftChild = d; a->rightChild = e; b->leftChild = f; // 调用 levelOrder 函数来进行前序遍历 levelOrder(root); return 0; }