二叉树是数据结构基本类型,节点最大的度为2,每一个节点通常有两个字树,称为左子树和右子树。如图
节点1的度为2,节点5的度为1,节点6,7度为0,称为叶节点。对于一个二叉树,我们访问其元素的方式有多种,下面介绍二叉树的四种遍历方式。
首先,先建立二叉树的结构体`
typedef struct treenode *binaryTree;
struct treenode
{
elementtype data;
binaryTree left;
binaryTree right;
};
- 先序遍历,以上图举例来说,先序遍历是从根节点开始,从左往右进行遍历,先输出树的根节点,然后在输出左子树,右子树。上图由先序遍历输出的结果为1 2 4 8 9 5 10 3 6 7 。
下面采用递归实现。下面采用递归实现。
void BinaryTree::preorder(binaryTree tree)
{
if (tree)
{
cout << tree->data;
preorder(tree->left);
preorder(tree->right);
}
}
2.中序遍历,中序遍历是先输出左字树,然后是根节点,再是右子树。输出顺序8 4 9 2 10 5 1 6 3 7 。程序如下:
void BinaryTree::inorder(binaryTree tree)
{
if (tree)
{
inorder(tree->left);
cout << tree->data;
inorder(tree->right);
}
}
3.后序遍历,后序遍历是先输出左字树,再输出右子树,再输出根节点。输出顺序为8 9 4 10 5 2 6 7 3 1.程序如下:
void BinaryTree::postorder(binaryTree tree)
{
if (tree)
{
postorder(tree->left);
postorder(tree->right);
cout << tree->data;
}
}
4.层序遍历,层序遍历是按照树的结构一层一层从左往右输出。输出顺序为1 2 3 4 5 6 7 8 9 10 。采用非递归实现,程序如下:
void BinaryTree::levelorder(binaryTree tree)
{
queue <binaryTree> q;
binaryTree T;
if (!tree) return;
q.push(tree);
while (!q.empty())
{
T = q.front();
q.pop();
cout << T->data;
if (T->left) q.push(T->left);
if (T->right) q.push(T->right);
}
}