1. 二叉树结点结构定义如下:
// 树节点定义
struct TreeNode {
int data;
TreeNode* lChild;
TreeNode* rChild;
};
2. 二叉树的基本操作函数如下:
- TreeNode* createBinTree(); // 先序创建二叉树(递归)
- void preOrderTraverse(TreeNode* head); // 先序遍历(递归)
- void inOrderTraverse(TreeNode* head); // 中序遍历(递归)
- void postOrderTraverse(TreeNode* head); // 后序遍历(递归)
- void preOrderTraverse_1(TreeNode* head); // 先序遍历(非递归)
- void inOrderTraverse_1(TreeNode* head); // 中序遍历(非递归)
- void postOrderTraverse_1(TreeNode* head); // 后序遍历(非递归)
3. 具体代码实现如下:
#include <iostream>
#include <stack>
using namespace std;
// 树节点定义
struct TreeNode {
int data;
TreeNode* lChild;
TreeNode* rChild;
};
// 先序创建二叉树(递归)
TreeNode* createBinTree() {
TreeNode* head = NULL;
int val = 0;
cin >> val;
if (val != 0) {
head = new TreeNode;
head->data = val;
head->lChild = createBinTree();
head->rChild = createBinTree();
}
return head;
}
// 先序遍历(递归)
void preOrderTraverse(TreeNode* head) {
if (head) {
cout << head->data << " ";
preOrderTraverse(head->lChild);
preOrderTraverse(head->rChild);
}
}
// 中序遍历(递归)
void inOrderTraverse(TreeNode* head) {
if (head) {
inOrderTraverse(head->lChild);
cout << head->data << " ";
inOrderTraverse(head->rChild);
}
}
// 后序遍历(递归)
void postOrderTraverse(TreeNode* head) {
if (head) {
postOrderTraverse(head->lChild);
postOrderTraverse(head->rChild);
cout << head->data << " ";
}
}
// 先序遍历(非递归)
void preOrderTraverse_1(TreeNode* head) {
TreeNode* node = head;
stack<TreeNode*> nodeStack;
while (node != NULL || !nodeStack.empty()) {
while (node != NULL) {
cout << node->data << " ";
nodeStack.push(node);
node = node->lChild;
}
if (!nodeStack.empty()) {
node = nodeStack.top();
nodeStack.pop();
node = node->rChild;
}
}
}
// 中序遍历(非递归)
void inOrderTraverse_1(TreeNode* head) {
TreeNode* node = head;
stack<TreeNode*> nodeStack;
while (node != NULL || !nodeStack.empty()) {
while (node != NULL) {
nodeStack.push(node);
node = node->lChild;
}
if (!nodeStack.empty()) {
node = nodeStack.top();
nodeStack.pop();
cout << node->data << " ";
node = node->rChild;
}
}
}
// 后序遍历(非递归)
void postOrderTraverse_1(TreeNode* head) {
// 待续。。
}
int main() {
TreeNode* head = NULL;
head = createBinTree();
cout << "preOrderTraverse: " << endl;
preOrderTraverse(head);
cout << endl << "inOrderTraverse: " << endl;
inOrderTraverse(head);
cout << endl << "postOrderTraverse: " << endl;
postOrderTraverse(head);
cout << endl << "preOrderTraverse_1: " << endl;
preOrderTraverse_1(head);
cout << endl << "inOrderTraverse_1: " << endl;
inOrderTraverse_1(head);
cout << endl;
system("pause");
return 0;
}
4. 运行结果截图如下: