二叉树层次遍历的举例
#include "stdafx.h" #include <iostream> #include <fstream>
#include <queue>
#include <stack> #include <Windows.h> using namespace std; typedef struct _Node { int data; struct _Node *left; struct _Node *right; _Node() { data = 0; left = NULL; right = NULL; } }Node, *_PNode; //***************************************层次遍历的举例********************************************begin //创建二叉树利用先序创建 /* 1 / \ 2 3 / \ / 4 5 6 / \ \ / \ 7 8 9 10 11 / \ 12 13 */ void CreateBitree(_PNode &pNode, fstream &fin) { int dat; fin>>dat; if(dat==0) { pNode = NULL; } else { pNode = new Node(); pNode->data=dat; CreateBitree(pNode->left, fin); CreateBitree(pNode->right, fin); } } //二叉树的自下而上,自右向左的遍历方法 void ReverseLevel(_PNode pRoot) { queue<_PNode> q; stack<_PNode> s; _PNode pNode = NULL; if (NULL == pRoot) { return; } q.push(pRoot); while (!q.empty()) { pNode = q.front(); q.pop(); s.push(pNode); if (NULL != pNode->left) { q.push(pNode->left); } if (NULL != pNode->right) { q.push(pNode->right); } } while (!s.empty()) { pNode = s.top(); s.pop(); cout<<pNode->data<<" "; } cout<<endl; } //统计二叉树中度为1的节点的个数,层次遍历 int CountOneDepth(_PNode pRoot) { queue<_PNode> q; _PNode pNode = NULL; int count = 0; if (NULL == pRoot) { return count; } q.push(pRoot); while (!q.empty()) { pNode = q.front(); q.pop(); if ((NULL != pNode->left && NULL == pNode->right) || (NULL == pNode->left && NULL != pNode->right)) { count++; } if (NULL != pNode->left) { q.push(pNode->left); } if (NULL != pNode->right) { q.push(pNode->right); } } return count; } //查找二叉树最大宽度 int FindMaxWidth(_PNode pRoot) { _PNode q[100] = {0}; _PNode pNode = NULL; int front = 0; int rear = 0; int last = 0; int width = 0; int temp = 0; if (NULL == pRoot) { return width; } q[rear] = pRoot; while (front <= last) { pNode = q[front++]; temp++; if (NULL != pNode->left) { q[++rear] = pNode->left; } if (NULL != pNode->right) { q[++rear] = pNode->right; } if (front > last) { last = rear; if (temp > width) { width = temp; } temp = 0; } } return width; } //***************************************层次遍历的举例********************************************end //辅助函数,设置控制台的颜色 void SetConsoleTextColor(WORD dwColor) { HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE == handle) { return; } SetConsoleTextAttribute(handle, dwColor); } int _tmain(int argc, _TCHAR* argv[]) { _PNode pRoot1 = NULL; SetConsoleTextColor(FOREGROUND_GREEN | FOREGROUND_INTENSITY); fstream fin("level.txt"); CreateBitree(pRoot1, fin); cout<<endl<<"******************层次遍历举例********************"<<endl; cout<<endl<<"二叉树的自下而上,自右向左的遍历"<<endl; ReverseLevel(pRoot1); cout<<endl<<"二叉树中度为1的节点个数:"<<CountOneDepth(pRoot1)<<endl; cout<<endl<<"二叉树中最大的宽度为 :"<<FindMaxWidth(pRoot1)<<endl; cout<<endl; return 0; }
运行界面如下:
建造二叉树的level.txt为:
1 2 4 7 12 0 0 0 8 0 13 0 0 5 0 9 0 0 3 6 10 0 0 11 0 0 0