树的创建和遍历

递归树前序遍历

前序遍历非递归

层次遍历

节点数

层次数

先序建树

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <stack>
#include <queue>
#include <malloc.h>
using namespace std;
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef struct node *link;
struct node
{
    char data;//数据域
    link l;//左孩子
    link r;//右孩子
};
//递归树前序遍历
void Traverse1(link tree)
{
    if(tree)
    {
        //先输出根结点
        printf("%c ", tree->data);
        //再递归其左子树
        Traverse1(tree->l);
        //再递归其右子树
        Traverse1(tree->r);
    }

}
//前序遍历非递归
void Traverse2(link tree)
{
    stack<link> s;
    //将根节点推入栈
    s.push(tree);
    //在栈不空时
    while(!s.empty())
    {
        //输出节点
        printf("%c ", s.top()->data);
        //取栈顶元素
        tree = s.top();
        //将栈顶的元素推出栈
        s.pop();
        //如果该节点的右孩子存在,将右孩子压入栈
        if(tree->r)
            s.push(tree->r);
        //如果该节点的左孩子存在,将左孩子压入栈
        if(tree->l)
            s.push(tree->l);
    }
}
//层次遍历
void Traverse3(link tree)
{
    queue<link> q;
    //把根节点放入队列
    q.push(tree);
    //当队列非空时
    while(!q.empty())
    {
        //将队头元素输出
        printf("%c ", q.front()->data);
        //tree指向队头
        tree = q.front();
        //将队头元素删除
        q.pop();
        //若其左孩子非空,将左孩子放入队列
        if(tree->l)
            q.push(tree->l);
        //若其右孩子非空,将右孩子放入队列
        if(tree->r)
            q.push(tree->r);
    }
}
//节点数
int Count(link tree)
{
    if(!tree)
        return 0;
    //遍历该节点,节点数加1,再遍历该节点的左孩子和右孩子
    return Count(tree->l) + Count(tree->r) + 1;
}
//层次数
int Height(link tree)
{
    if(!tree)
        return 0;
    //递归在该节点的左孩子和右孩子中找出最大高度
    return max(Height(tree->l), Height(tree->r)) + 1;
}
//先序建树
link CreateTree()
{
    char ch;
    link tree;
    scanf("%c", &ch);
    if(ch == '1')
        return NULL;
    tree = (link)malloc(sizeof(struct node));
    tree->data = ch;
    tree->l = CreateTree();
    tree->r = CreateTree();
    return tree;
}
int main()
{
    link tree;
    tree = CreateTree();
    Traverse1(tree);
    printf("\n");
    Traverse2(tree);
    printf("\n");
    Traverse3(tree);
    printf("\n");
    printf("节点数 %d\n", Count(tree));
    printf("层次 %d\n", Height(tree));
    return 0;
}
//输入的样例
//EDBA11C111HF1G111

猜你喜欢

转载自blog.csdn.net/weixin_42480264/article/details/81632860