求二叉树宽度
来源:互联网 发布:什么是大数据交易平台 编辑:程序博客网 时间:2024/05/16 23:12
#include <iostream>#include <stack>using namespace std;struct Node{ int m_nData; Node *m_pLeft; Node *m_pRight; }; void xCalcWidth(Node *pRoot, int *piWidth, int nDepth){if (pRoot==NULL){return;}piWidth[nDepth]++;xCalcWidth(pRoot->m_pLeft, piWidth, nDepth+1);xCalcWidth(pRoot->m_pRight, piWidth, nDepth+1);}int calcBinaryTreeWidth(Node *pRoot, int iNumNodes){if (pRoot==NULL){return -1;}int *piWidth = new int[iNumNodes];memset(piWidth, 0, iNumNodes*sizeof(int));xCalcWidth(pRoot, piWidth, 0);int iWidth = -1;for (int i=0; i<iNumNodes; i++){iWidth = (piWidth[i]>iWidth? piWidth[i]:iWidth);}return iWidth;}int main(){Node *node1 = new Node; node1->m_nData = 1;Node *node2 = new Node; node2->m_nData = 2;Node *node3 = new Node; node3->m_nData = 3;Node *node4 = new Node; node4->m_nData = 4;Node *node5 = new Node; node5->m_nData = 5;Node *node6 = new Node; node6->m_nData = 6;Node *node7 = new Node; node7->m_nData = 7;node1->m_pLeft = node2; node1->m_pRight = node3;node2->m_pLeft = node4; node2->m_pRight = node5;node3->m_pLeft = node6; node3->m_pRight = NULL;node4->m_pLeft = node7; node4->m_pRight = NULL;node5->m_pLeft = NULL; node5->m_pRight = NULL;node6->m_pLeft = NULL; node6->m_pRight = NULL;node7->m_pLeft = NULL; node7->m_pRight = NULL;cout<<calcBinaryTreeWidth(node1, 7)<<endl;}