c++二叉树的建立与遍历完整代码
时间: 2023-12-18 17:05:13 浏览: 110
以下是C++二叉树的建立与遍历的完整代码:
```cpp
#include <iostream>
#include <queue>
using namespace std;
// 二叉树节点结构体
struct TreeNode {
int m_nRootId; // 节点值
TreeNode* m_pLeftChild; // 左子节点指针
TreeNode* m_pRightChild; // 右子节点指针
TreeNode(int val) : m_nRootId(val), m_pLeftChild(NULL), m_pRightChild(NULL) {}
};
// 二叉树类
class BinaryTree {
public:
BinaryTree() : m_pTreeNode(NULL) {}
~BinaryTree() { destroy(m_pTreeNode); }
// 插入节点
void insert(int val) {
if (m_pTreeNode == NULL) {
m_pTreeNode = new TreeNode(val);
return;
}
TreeNode* p = m_pTreeNode;
while (p != NULL) {
if (val < p->m_nRootId) {
if (p->m_pLeftChild == NULL) {
p->m_pLeftChild = new TreeNode(val);
return;
}
p = p->m_pLeftChild;
} else {
if (p->m_pRightChild == NULL) {
p->m_pRightChild = new TreeNode(val);
return;
}
p = p->m_pRightChild;
}
}
}
// 前序遍历
void preorderTraversal(TreeNode* node) {
if (node == NULL) return;
cout << node->m_nRootId << " ";
preorderTraversal(node->m_pLeftChild);
preorderTraversal(node->m_pRightChild);
}
// 中序遍历
void InorderTraversal(TreeNode* node) {
if (node == NULL) return;
InorderTraversal(node->m_pLeftChild);
cout << node->m_nRootId << " ";
InorderTraversal(node->m_pRightChild);
}
// 后序遍历
void postorderTraversal(TreeNode* node) {
if (node == NULL) return;
postorderTraversal(node->m_pLeftChild);
postorderTraversal(node->m_pRightChild);
cout << node->m_nRootId << " ";
}
// 广度优先遍历
void levelOrderTraversal() {
if (m_pTreeNode == NULL) return;
queue<TreeNode*> TreeStack;
TreeNode* p = NULL;
TreeStack.push(m_pTreeNode);
while (!TreeStack.empty()) {
p = TreeStack.front();
TreeStack.pop();
if (p->m_pLeftChild != NULL) TreeStack.push(p->m_pLeftChild);
if (p->m_pRightChild != NULL) TreeStack.push(p->m_pRightChild);
cout << p->m_nRootId << " ";
}
}
private:
TreeNode* m_pTreeNode;
// 销毁二叉树
void destroy(TreeNode* node) {
if (node == NULL) return;
destroy(node->m_pLeftChild);
destroy(node->m_pRightChild);
delete node;
}
};
int main() {
BinaryTree tree;
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(2);
tree.insert(4);
tree.insert(6);
tree.insert(8);
cout << "前序遍历:";
tree.preorderTraversal(tree.m_pTreeNode);
cout << endl;
cout << "中序遍历:";
tree.InorderTraversal(tree.m_pTreeNode);
cout << endl;
cout << "后序遍历:";
tree.postorderTraversal(tree.m_pTreeNode);
cout << endl;
cout << "广度优先遍历:";
tree.levelOrderTraversal();
cout << endl;
return 0;
}
```
阅读全文