二叉树的深度优先搜索

(一)基本思想

bitree.png

分析:使用两个栈来存放节点元素,栈1用来存放未遍历过的节点,栈2用来存放遍历的节点。

bitree-dfs.jpg

具体步骤:
(1)把第一个节点压进栈1。见图(a)
(2)把栈1中的栈顶节点弹出,压进栈2;若栈1为空,且被弹出节点有子节点,则把被弹出节点的子节点按从右到左的顺序压进栈1。见图(b)
(3)重复步骤2,直至栈1为空。见图(c)~图(h)
(4)至此,遍历过程结束。遍历顺序就是栈2中节点的入栈顺序。

(二)C++实现代码

#include <iostream>
#include <stack>
using namespace std;

struct node
{
    int data;
    node *left;
    node *right;
};

void dfs(int a[], int size)
{
    stack<node *> visited, unvisited;
    node nodes[size];
    node *current;

    // 构建二叉树
    for(int i = 0; i < size; i++)
    {
        nodes[i].data = a[i];
        // 左子节点
        int child = 2 * i + 1;
        if(child < size)
        {
            nodes[i].left = &nodes[child];
        }
        else
        {
            nodes[i].left = NULL;
        }

        // 右子节点
        child++;
        if(child < size)
        {
            nodes[i].right = &nodes[child];
        }
        else
        {
            nodes[i].right = NULL;
        }
    }

    // 先把第0个节点加到unvisited栈中
    unvisited.push(&nodes[0]);
    while (!unvisited.empty())
    {
        current = unvisited.top();
        unvisited.pop();

        if(NULL != current->right)
        {
            // 把右子节点先压入unvisited栈,因为右子节点的访问次序在左子节点之后
            unvisited.push(current->right);
        }

        if(NULL != current->left)
        {
            unvisited.push(current->left);
        }

        visited.push(current);

        cout << current->data << "  ";
    }
}

int main(int argc, const char * argv[])
{
    int a[] = {0, 1, 2, 3, 4, 5, 6};
    int size = sizeof(a)/sizeof(int);
    dfs(a, size);
    return 0;
}

运行结果:

0  1  3  4  2  5  6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值