二叉树遍历

本文详细介绍了二叉树的构建、遍历方法及树的销毁过程。通过使用C++,展示了如何创建二叉树节点,实现深度优先搜索(DFS)的递归与迭代版本,宽度优先搜索(BFS),并提供了树的打印与销毁函数。通过具体实例演示了这些函数的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include <queue>
#include<stack>
using namespace std;

struct Node
{
    int nVal;
    Node *pLeft;
    Node *pRight;

    Node(int val,Node* left=NULL,Node * right=NULL):nVal(val),pLeft(left),pRight(right){}; //构造
};
// 析构
void DestroyTree(Node *pRoot)   
{
    if (pRoot==NULL)
        return;

    Node* pLeft=pRoot->pLeft;
    Node* pRight=pRoot->pRight;

    delete pRoot;
    pRoot =NULL;

    DestroyTree(pLeft);
    DestroyTree(pRight);

}


// 用queue实现的BFS
void BFS(Node *pRoot)
{
    if (pRoot==NULL)
        return;

    queue<Node*> Q;

    Q.push(pRoot);

    while(!Q.empty())
    {

        Node *node = Q.front();

        cout<<node->nVal<<"->";
        if (node->pLeft!=NULL)
        {
            Q.push(node->pLeft);
        }

        if (node->pRight!=NULL)
        {
            Q.push(node->pRight);
        }

        Q.pop();
    }

    cout<<endl;
}


// DFS的递归实现
void DFS_Recursive(Node* pRoot)
{
    if (pRoot==NULL)
        return;

    cout<<pRoot->nVal<<" ";

    if (pRoot->pLeft!=NULL)    
        DFS_Recursive(pRoot->pLeft);


    if (pRoot->pRight!=NULL)
        DFS_Recursive(pRoot->pRight);

}

// DFS的迭代实现版本(stack)
void DFS_Iterative(Node* pRoot)
{
    if (pRoot==NULL)
        return;

    stack<Node*> S;
    S.push(pRoot);

    while (!S.empty())
    {
        Node *node=S.top();
        cout<<node->nVal<<",";

        S.pop();

        if (node->pRight!=NULL)
        {
            S.push(node->pRight);
        }

        if (node->pLeft!=NULL)
        {
            S.push(node->pLeft);
        }

    }

}


// 打印树的信息
void PrintTree(Node* pRoot)
{
    if (pRoot==NULL)
        return;

    cout<<pRoot->nVal<<" ";

    if (pRoot->pLeft!=NULL)
    {
        PrintTree(pRoot->pLeft);
    }

    if (pRoot->pRight!=NULL)
    {
        PrintTree(pRoot->pRight);
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    Node *node1=new Node(4);
    Node *node2=new Node(5);
    Node *node3=new Node(6);

    Node* node4=new Node(2,node1,node2);
    Node* node5=new Node(3,node3);
    Node* node6=new Node(1,node4,node5);

    Node *node7=new Node(7);
    Node *node8=new Node(8);
    node1->pLeft=node7;
    node1->pRight=node8;

    Node *node10=new Node(10);
    Node *node11=new Node(11);
    node2->pLeft=node10;
    node2->pRight=node11;

    Node* pRoot = node6;
    //PrintTree(pRoot);
    DFS_Recursive(pRoot);

    //DFS_Iterative(pRoot);


//    BFS(pRoot);
    DestroyTree(pRoot);
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值