当前位置: 编程技术>c/c++/嵌入式
C语言实现二叉树遍历的迭代算法
来源: 互联网 发布时间:2014-10-28
本文导语: 本文实例讲述了C语言实现二叉树遍历的迭代算法,是数据结构算法中非常经典的一类算法。分享给大家供大家参考。 具体实现方法如下: 二叉树中序遍历的迭代算法: #include #include using namespace std; struct Node { Node(in...
本文实例讲述了C语言实现二叉树遍历的迭代算法,是数据结构算法中非常经典的一类算法。分享给大家供大家参考。
具体实现方法如下:
二叉树中序遍历的迭代算法:
#include
#include
using namespace std;
struct Node {
Node(int i, Node* l = NULL, Node* r = NULL) : item(i), left(l), right(r) {}
int item;
Node* left;
Node* right;
};
Node* construct() {
Node* node6 = new Node(16);
Node* node5 = new Node(12);
Node* node4 = new Node(8);
Node* node3 = new Node(4);
Node* node2 = new Node(14, node5, node6);
Node* node1 = new Node(6, node3, node4);
Node* node0 = new Node(10, node1, node2);
return node0;
}
//递归算法
void inorder(Node *root)
{
if (root == NULL)
return;
inorder(root->left);
cout item right);
}
void preorder(Node *root)
{
if(root == NULL)
return;
cout item left);
preorder(root->right);
}
void postorder(Node *root)
{
if (root == NULL)
return;
postorder(root->left);
postorder(root->right);
cout item left && pre != node->right)
{
if (node->right)
nstack.push(node->right);
if (node->left)
nstack.push(node->left);
}
if (node->left == NULL && node->right == NULL
|| pre == node->left || pre == node->right)
{
cout item right;
}
}
void preorder3(Node *root)
{
if (root == NULL)
return;
stack nstack;
nstack.push(root);
Node *node = NULL;
while (!nstack.empty())
{
node = nstack.top();
nstack.pop();
cout item right)
nstack.push(node->right);
if (node->left)
nstack.push(node->left);
}
}
//迭代算法
void inorder2(Node *root)
{
if(root == NULL)
return;
stack nstack;
nstack.push(root);
Node *next = root->left;
while (next != NULL || !nstack.empty())
{
while (next != NULL)
{
nstack.push(next);
next = next->left;
}
next = nstack.top();
nstack.pop();
cout item right;
}
}
int main()
{
Node *root = construct();
cout