二叉树 深度优先搜索 宽度优先搜索
2016-02-14 17:36
417 查看
/****************************** 作者:cncoderalex 博客:http://blog.csdn.net/cncoderalex *******************************/ #include<iostream> #include<queue> #include<stack> using namespace std; struct Node { int Data; Node *pLeft; Node *pRight; }; Node *CreateNode(int Data) { Node *pNode = new Node(); pNode->Data = Data; pNode->pLeft = NULL; pNode->pRight = NULL; return pNode; } Node *CreateTree(int Ary[], int Len) { if (Len <= 0) return NULL; Node *pRoot = CreateNode(Ary[0]); std::queue<Node *> que; que.push(pRoot); int i = 0; for (i = 2; i < Len; i += 2) { Node *pLeft = CreateNode(Ary[i - 1]); Node *pRight = CreateNode(Ary[i]); Node *pParent = que.front(); que.pop(); pParent->pLeft = pLeft; pParent->pRight = pRight; que.push(pLeft); que.push(pRight); } if (i == Len) { Node *pLeft = CreateNode(Ary[i - 1]); Node *pParent = que.front(); que.pop(); pParent->pLeft = pLeft; } return pRoot; } void DestroyTree(Node *&pRoot) { if (pRoot == NULL) return; if (pRoot->pLeft) DestroyTree(pRoot->pLeft); if (pRoot->pRight) DestroyTree(pRoot->pRight); delete pRoot; pRoot = NULL; } void BFS(Node *pRoot) { if (pRoot == NULL) return; std::queue<Node *> que; que.push(pRoot); while (!que.empty()) { Node *pNode = que.front(); que.pop(); if (pNode->pLeft) que.push(pNode->pLeft); if (pNode->pRight) que.push(pNode->pRight); printf("%d ", pNode->Data); } printf("\n"); } void DFS(Node *pRoot) { if (pRoot == NULL) return; std::stack<Node *> sk; Node *pNode = pRoot; while (true) { while (pNode) { printf("%d ", pNode->Data); sk.push(pNode); pNode = pNode->pLeft; } bool bFound = false; while (!sk.empty()) { pNode = sk.top(); sk.pop(); if (pNode->pRight != NULL) { pNode = pNode->pRight; bFound = true; break; } } if (!bFound) break; } printf("\n"); } void DFS_Recursion(Node *pRoot) { if (pRoot == NULL) return; printf("%d ", pRoot->Data); if (pRoot->pLeft != NULL) { DFS_Recursion(pRoot->pLeft); } if (pRoot->pRight != NULL) { DFS_Recursion(pRoot->pRight); } } int main() { printf("http://blog.csdn.net/cncoderalex"); printf("\n"); int Ary[] = { 5, 3, 2, 8, 10, 15, 12, 14, 18 }; Node *pRoot = CreateTree(Ary, sizeof(Ary) / sizeof(int)); BFS(pRoot); DFS(pRoot); DFS_Recursion(pRoot); DestroyTree(pRoot); system("pause"); return 0; }
相关文章推荐
- PHP代码段
- KM(n^4)模板
- 栈
- http://blog.csdn.net/chenli522/article/details/17001823
- 从点到面,给Button的属性动画
- iOS IM开发准备工作(一)XML解析
- rocketmq3.26研究之Failover下producer的表现
- iOS开发笔记-圆滑的曲线
- 从字符数组中删除字符
- 条件变量
- HA 高可用集群
- 序列化和反序列化
- Eclipse快捷键1
- 利用SVN的post-commit钩子实现多项目自动同步
- iOS字符串处理详解
- 【Dubbo实战】 Dubbo+Zookeeper+Spring整合应用篇-Dubbo基于Zookeeper实现分布式服务(转)
- sublime text3
- 设计模式-工厂
- MATLAB插值方法简介
- c++基础——类的大小