原文链接:http://blog.youkuaiyun.com/zhonghua18517/article/details/28238261
二叉树的深度优先遍历和先序遍历结果一样的。 思想是采用栈, 首先将根结点压入栈,如果栈不为空,而后出栈并输出当前结点中值,而后先把右子树压入栈,再把左子树压入栈,再判断栈是否为空,循环.....
步骤如下:
(1) 树的根结点入栈
(2)判断栈是否为空,不为空,则出栈,并输出出栈树结点的值
(3)出栈树结点的右子树入栈
(4)出栈树结点的左子树入栈
(5)循环回到(2)
创建如上树。详见前面二叉树的创建。
代码如下:
- // Tree_depth_breadth.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- typedef int type;
- //定义二叉树结点
- typedef struct node
- {
- type data;
- struct node *lchild;
- struct node *rchild;
- }node,*bTree;
- //建立元素为树节点的栈
- typedef struct stack
- {
- bTree tree;
- struct stack *next;
- }stack,*pStack;
- //初始化栈
- void InitStack(pStack &s)
- {
- s=(pStack)malloc(sizeof(stack));
- if(NULL==s)
- {
- cout<<"申请内存失败!"<<endl;
- exit(-1);
- }
- s->next=NULL;
- }
- //进栈
- void Push(pStack s,bTree data)
- {
- pStack temp=(pStack)malloc(sizeof(stack));
- if(NULL==temp)
- {
- cout<<"申请内存失败!"<<endl;
- exit(-1);
- }
- temp->tree=data;
- temp->next=s->next;
- s->next=temp;
- }
- //出栈
- pStack Pop(pStack s)
- {
- pStack temp=s->next;
- if(NULL==temp)
- {
- cout<<"栈为空!"<<endl;
- exit(-1);
- }
- s->next=temp->next;
- return temp;
- }
- //深度优先遍历 类似于先序遍历
- void DepthFS(bTree T,pStack s)
- {
- Push(s,T);
- while(NULL!=s->next)
- {
- pStack temp=Pop(s);
- cout<<temp->tree->data<<" ";
- if(NULL!=temp->tree->rchild)
- Push(s,temp->tree->rchild);
- if(NULL!=temp->tree->lchild)
- Push(s,temp->tree->lchild);
- }
- }
- //先序遍历
- void PreOrder(bTree T)
- {
- if(NULL!=T)
- {
- cout<<T->data<<" ";
- PreOrder(T->lchild);
- PreOrder(T->rchild);
- }
- }
- //出栈
- //创建二叉树
- void CreateTree(bTree &T)
- {
- type ch;
- cin>>ch;
- if(0==ch)
- {
- T=NULL;
- }
- else
- {
- T=(bTree)malloc(sizeof(node));
- if(NULL==T)
- {
- cout<<"申请内存失败!"<<endl;
- exit(-1);
- }
- T->data=ch;
- CreateTree(T->lchild); //创建左子树
- CreateTree(T->rchild); //创建右子树
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- bTree T=NULL;
- pStack s=NULL;
- CreateTree(T);
- InitStack(s);
- PreOrder(T);
- cout<<endl;
- DepthFS(T,s);
- return 0;
- }
结果: