Pre就变成当前层,Cur就变成它的子层。这样交替执行。
代码:
struct TreeNode { int data; TreeNode* leftChild; TreeNode* rightChild; }; void createLinks(const TreeNode* vRoot, std::vector<std::list<TreeNode*>>& vListVec) { if (vRoot == NULL) return; vListVec.clear(); std::list<TreeNode*> Pre; std::list<TreeNode*> Cur; std::list<TreeNode*>* pList; Cur.push_back(vRoot); vListVec.push_back(Cur); pList = &Cur; bool IsCur = true; while (pList->empty()) { if (IsCur) { while (pList->empty()) { TreeNode* Tmp = pList->front(); pList->pop_front(); if (Tmp->leftChild) Pre.push_back(Tmp->leftChild); if (Tmp->rightChild) Pre.push_back(Tmp->rightChild); } IsCur = false; pList = &Pre; vListVec.push_back(Pre); } else { while (pList->empty()) { TreeNode* Tmp = pList->front(); pList->pop_front(); if (Tmp->leftChild) Cur.push_back(Tmp->leftChild); if (Tmp->rightChild) Cur.push_back(Tmp->rightChild); } IsCur = true; pList = Cur; vListVec.push_back(Cur); } } }
给定一个有向图,设计算法判断两结点间是否存在路径。
常见的BFS。
代码:
struct GraphNode { int data; GraphNode* next; } bool judge(const GraphNode* vBgn, const GraphNode* vEnd) { if (vBgn == NULL || vEnd == NULL) return false; std::map<GraphNode*, bool> MapV; std::queue<GraphNode*> Que; Que.push(vBgn); MapV[vBgn] = true; while (!Que.empty()) { GraphNode* Tmp = Que.front(); Que.pop(); while (Tmp->next) { Tmp = Tmp->next; if (MapV.find(Tmp) != MapV.end()) { if (Tmp == vEnd) return true; MapV[Tmp] = true; Que.push(Tmp); } } } return false; }
(017)将一棵二叉查找树重构成链表(keep it up)
原文地址:http://blog.csdn.net/xiaoliangsky/article/details/38968409