#include "stdafx.h"#include#include using namespace std;typedef struct _Node{ int data; struct _Node *left; struct _Node *right; int bf; //平衡因子 _Node() { data = 0; left = NULL; right = NULL; bf = 0; }}Node, *_PNode;//创建二叉树利用先序创建/* 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); }}//**************************************求各结点的平衡因子**************************************begin//递归求二叉树的深度int Depth(_PNode pNode){ if (NULL != pNode) { int hl = Depth(pNode->left); int hr = Depth(pNode->right); return hl > hr ? hl + 1: hr + 1; } return 0;}//递归求二叉树每个结点的平衡因子void Balance(_PNode pNode){ if (NULL != pNode) { Balance(pNode->left); Balance(pNode->right); int hl = Depth(pNode->left); int hr = Depth(pNode->right); pNode->bf = hl - hr; }}//前序递归遍历void PreTravelTree(_PNode pRoot) { if(pRoot) { cout< data<<"("< bf<<")"<<" "; PreTravelTree(pRoot->left); PreTravelTree(pRoot->right); }}//中序递归遍历void MidTravelTree(_PNode pRoot) { if(pRoot) { MidTravelTree(pRoot->left); cout< data<<"("< bf<<")"<<" "; MidTravelTree(pRoot->right); }}//**************************************求各结点的平衡因子**************************************endint _tmain(int argc, _TCHAR* argv[]){ _PNode pRoot = NULL; fstream fin("tree.txt"); CreateBitree(pRoot, fin); Balance(pRoot); cout<<"前序:"; PreTravelTree(pRoot); cout< <<"后序:"; MidTravelTree(pRoot); cout<
运行界面如下:
建造二叉树用到的tree.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