您的位置:首页 > 其它

二叉树各种遍历的实现(递归、非递归、层次、高度和节点数目)

2015-08-27 15:07 597 查看
以下代码将实现下列函数:

(1)建树

(2)递归前序遍历

(3)递归中序遍历

(4)递归后序遍历

(5)非递归前序遍历

(6)非递归中序遍历

(7)非递归后序遍历

(8)层次遍历

(9)树的高度

(10)节点数目

#include<stdio.h>
#include<stack>
#include<stdlib.h>
#include<deque>

using namespace std;

struct BinaryTree
{
char c;
BinaryTree *left;
BinaryTree *right;
};

void creatTree(BinaryTree **root)
{
char c;
scanf("\n%c", &c);

if(c == '#')
*root = NULL;
else
{
*root = (BinaryTree*)malloc(sizeof(BinaryTree));
(*root)->c = c;
creatTree(&((*root)->left));
creatTree(&((*root)->right));
}

}

void preOrder(BinaryTree *root)
{
if(root == NULL)
return;

printf("%c ", root->c);
preOrder(root->left);
preOrder(root->right);

}

void inOrder(BinaryTree *root)
{
if(root == NULL)
return;

inOrder(root->left);
printf("%c ", root->c);
inOrder(root->right);
}

void postOrder(BinaryTree *root)
{
if(root == NULL)
return;

postOrder(root->left);
postOrder(root->right);
printf("%c ", root->c);
}

void preOrder_nonRecursive(BinaryTree *root)
{
if(root == NULL)
return;

stack<BinaryTree*> s;
BinaryTree *curr = root;

while(curr != NULL || !s.empty())
{
while(curr != NULL)
{
printf("%c ", curr->c);
s.push(curr);
curr = curr->left;
}

if(!s.empty())
{
curr = s.top();
s.pop();
curr = curr->right;
}
}
}

void inOrder_nonRecursive(BinaryTree *root)
{
if(root == NULL)
return;

stack<BinaryTree*> s;
BinaryTree *curr = root;

while(curr != NULL || !s.empty())
{
while(curr != NULL)
{

s.push(curr);
curr = curr->left;
}

if(!s.empty())
{
curr = s.top();
printf("%c ", curr->c);
s.pop();
curr = curr->right;
}
}
}
void postOrder_nonRecursive(BinaryTree *root)
{
if(root == NULL)
return;

stack<BinaryTree*> s;
BinaryTree *curr = root;
BinaryTree *preVisited = NULL;

while(curr != NULL || !s.empty())
{
while(curr != NULL)
{
s.push(curr);
curr = curr->left;
}

curr = s.top();
if(curr->right == NULL || curr->right == preVisited)
{
printf("%c ", curr->c);
preVisited = curr;
s.pop();
curr = NULL;
}
else
{
curr = curr->right;
}
}
}

void levelOrder(BinaryTree *root)
{
if(root == NULL)
return;

deque<BinaryTree *> s;
s.push_back(root);

while(s.size())
{
BinaryTree *node = s.front();
s.pop_front();
printf("%c ", node->c);

if(node->left)
s.push_back(node->left);
if(node->right)
s.push_back(node->right);
}
}

int depth(BinaryTree *root)
{
if(root == NULL)
return 0;

int left = depth(root->left);
int right = depth(root->right);

return 1 + (left > right ? left : right);
}

int count(BinaryTree *root)
{
if(root == NULL)
return 0;

return 1 + count(root->left) + count(root->right);
}
int main()
{
BinaryTree *root = NULL;
creatTree(&root);

preOrder(root);
printf("\n");
inOrder(root);
printf("\n");
postOrder(root);
printf("\n");
preOrder_nonRecursive(root);
printf("\n");
inOrder_nonRecursive(root);
printf("\n");
postOrder_nonRecursive(root);
printf("\n");
levelOrder(root);
printf("\n");
printf("%d\n", depth(root));
printf("%d\n", count(root));
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息