二叉树的先序遍历(递归与非递归)

14 篇文章 0 订阅

二叉树的遍历

1.树的结构

在这里插入图片描述

2.递归遍历过程

在这里插入图片描述

3.非递归过程

在这里插入图片描述
在这里插入图片描述

4.实现

1.递归实现

void PreOrder(BtNode* p)
{
    if (p != NULL)
    {
        cout << p->data << "  ";
        PreOrder(p->leftchild);
        PreOrder(p->rightchild);
    }
}

2.非递归实现

void NicePreOrder(BtNode* ptr)
{
    if (ptr == NULL) return;
    stack<BtNode*> st;
    st.push(ptr);
    while (!st.empty())
    {
        ptr = st.top();
        st.pop();
        cout << ptr->data << "  ";
        if (ptr->rightchild)
        {
            st.push(ptr->rightchild);
        }
        if (ptr->leftchild)
        {
            st.push(ptr->leftchild);
        }
    }
}

5.完整代码

#include <iostream>
#include <stack>

using namespace std;

typedef char ElemType;

typedef struct BtNode
{
    ElemType data;
    struct BtNode* leftchild;
    struct BtNode* rightchild;
}BtNode, * BinaryTree;

//非递归实现先序遍历
void NicePreOrder(BtNode* ptr)
{
    if (ptr == NULL) return;
    stack<BtNode*> st;
    st.push(ptr);
    while (!st.empty())
    {
        ptr = st.top();
        st.pop();
        cout << ptr->data << "  ";
        if (ptr->rightchild)
        {
            st.push(ptr->rightchild);
        }
        if (ptr->leftchild)
        {
            st.push(ptr->leftchild);
        }
    }
}
//递归实现二叉树的先序遍历
void PreOrder(BtNode* p)
{
    if (p != NULL)
    {
        cout << p->data << "  ";
        PreOrder(p->leftchild);
        PreOrder(p->rightchild);
    }
}

//---------------二叉树的构建--------------
BtNode* BuyNode()
{
    BtNode* s = (BtNode*)malloc(sizeof(BtNode));
    if (NULL == s) exit(1);

    memset(s, sizeof(BtNode), 0);
}
//先构造左子树,再构造右子树
BtNode* CBTree()
{
    BtNode* s = NULL;
    ElemType elem;
    cin >> elem;
    if (elem != '#')
    {
        s = BuyNode();
        s->data = elem;
        s->leftchild = CBTree();
        s->rightchild = CBTree();
    }

    return s;
}
int main()
{
    BinaryTree root = CBTree();

    PreOrder(root);
    cout << endl;

    return 0;
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值