2
/ \
1 3
2 1 3
//main1.cpp
/**
* @brief 先序遍历二叉树
*
* @param tree
*/
void PreOrderPrintBinTree(BinTree tree)
{
if (tree != nullptr)
{
<< tree->data << endl;
cout (tree->left);
PreOrderPrintBinTree(tree->right);
PreOrderPrintBinTree}
}
1 2 3
//main1.cpp
/**
* @brief 中序遍历二叉树
*
* @param tree
*/
void InOrderPrintBinTree(BinTree tree)
{
if (tree != nullptr)
{
(tree->left);
InOrderPrintBinTree<< tree->data << endl;
cout (tree->right);
InOrderPrintBinTree}
}
1 3 2
//main1.cpp
/**
* @brief 后序遍历二叉树
*
* @param tree
*/
void PostOrderPrintBinTree(BinTree tree)
{
if (tree != nullptr)
{
(tree->left);
PostOrderPrintBinTree(tree->right);
PostOrderPrintBinTree<< tree->data << endl;
cout }
}
上面的三种方式都是递归形式
深度优先遍历借助栈、广度优先遍历(层次遍历)借助队列
//main2.cpp
/**
* @brief 先序遍历二叉树 非空节点则入栈 遇见空节点则出栈 出栈去右子树
*
* @param tree
*/
void PreOrderPrintBinTree(BinTree tree)
{
<BinTree> stack;
vector= tree;
BinTree ptr while (ptr || !stack.empty())
{
if (ptr)
{
<< ptr->data << endl; //先访问再入栈
cout //当前节点入栈
.push_back(ptr);
stack//去左孩子
= ptr->left;
ptr }
else
{
//栈顶元素出栈
= stack[stack.size() - 1];
BinTree top .erase(stack.end() - 1);
stack//去右孩子
= top->right;
ptr }
}
}
/**
* @brief 中序遍历二叉树
*
* @param tree
*/
void InOrderPrintBinTree(BinTree tree)
{
<BinTree> stack;
vector= tree;
BinTree ptr while (ptr || !stack.empty())
{
if (ptr)
{
//当前节点入栈
.push_back(ptr);
stack//去左孩子
= ptr->left;
ptr }
else
{
//栈顶元素出栈
= stack[stack.size() - 1];
BinTree top .erase(stack.end() - 1);
stack= top;
ptr << ptr->data << endl;
cout //去右孩子
= top->right;
ptr }
}
}
/**
* @brief 后序遍历二叉树
*
* @param tree
*/
void PostOrderPrintBinTree(BinTree tree)
{
enum
{
,
LEFT
RIGHT};
<BinTree> node_stack;
vector<int> flag_stack; //二者同步记录,且记录现在的位置对于栈内的节点,在它们的左子树还是右子树
vector= tree;
BinTree ptr while (ptr || !node_stack.empty())
{
if (ptr == nullptr)
{
//看栈顶
= node_stack[node_stack.size() - 1];
BinTree peek int flag = flag_stack[flag_stack.size() - 1];
if (flag == RIGHT)
{ //从右子树回来的 则对根节点进行访问
<< peek->data << endl;
cout .erase(node_stack.end() - 1);
node_stack.erase(flag_stack.end() - 1);
flag_stack}
else
{ //从左子树回来的,则跳去右子树
= node_stack[node_stack.size() - 1]->right;
ptr [flag_stack.size() - 1] = RIGHT;
flag_stack}
continue;
}
//节点入栈
.push_back(ptr);
node_stack.push_back(LEFT); //要进入此节点的左子树
flag_stack//去左子树
= ptr->left;
ptr }
}
使用c++标准库队列queue<type>
//main3.cpp
/**
* @brief 层级遍历二叉树
*
* @param tree
*/
void LevelOrderPrintBinTree(BinTree &tree)
{
if (tree == nullptr)
return;
std::queue<BinTree> node_queue;
.push(tree);
node_queuewhile (!node_queue.empty())
{
= node_queue.front();
BinTree now_node .pop();
node_queue<< now_node->data << endl;
cout if (now_node->left)
{
.push(now_node->left);
node_queue}
if (now_node->right)
{
.push(now_node->right);
node_queue}
}
}