二叉树平衡因子应用举例
#include "stdafx.h" #include <fstream> #include <iostream> 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<<pRoot->data<<"("<<pRoot->bf<<")"<<" "; PreTravelTree(pRoot->left); PreTravelTree(pRoot->right); } } //中序递归遍历 void MidTravelTree(_PNode pRoot) { if(pRoot) { MidTravelTree(pRoot->left); cout<<pRoot->data<<"("<<pRoot->bf<<")"<<" "; MidTravelTree(pRoot->right); } } //**************************************求各结点的平衡因子**************************************end int _tmain(int argc, _TCHAR* argv[]) { _PNode pRoot = NULL; fstream fin("tree.txt"); CreateBitree(pRoot, fin); Balance(pRoot); cout<<"前序:"; PreTravelTree(pRoot); cout<<endl<<"后序:"; MidTravelTree(pRoot); cout<<endl; return 0; }
运行界面如下:
建造二叉树用到的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