题目:输入一棵二元树的根结点,求该树的深度。
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
例如:输入二元树:
8
/ /
6 10
// //
5 7 9 11
输出该树的深度3。
二元树的结点定义如下:
struct SBinaryTreeNode // a node of the binary tree
{
int m_nValue; // value of node
SBinaryTreeNode *m_pLeft; // left child of node
SBinaryTreeNode *m_pRight; // right child of node
};
思想:同[编程之美-07]主要考察还是层序遍历思想。
代码如下:
#include<iostream>
#include<deque>
using namespace std;
struct BSTreeNode
{
int m_nValue;
BSTreeNode *m_pleft;
BSTreeNode *m_pright;
};
int depthOfBSTree = 0;
void addBSTreeNode(BSTreeNode *&pCurrent, int value);
void levelOrderBSTree(BSTreeNode *pRoot);
int main()
{
BSTreeNode *pRoot = NULL;
addBSTreeNode(pRoot, 8);
addBSTreeNode(pRoot, 6);
addBSTreeNode(pRoot, 5);
addBSTreeNode(pRoot, 7);
addBSTreeNode(pRoot, 10);
addBSTreeNode(pRoot, 9);
addBSTreeNode(pRoot, 11);
levelOrderBSTree(pRoot);
cout<<depthOfBSTree<<endl;
return 0;
}
void levelOrderBSTree(BSTreeNode *pRoot)
{
if(pRoot == NULL)
return ;
deque<BSTreeNode*> que;
que.push_back(pRoot);
BSTreeNode *last, *nlast;
last = pRoot;
nlast = pRoot;
while(que.size() != 0)
{
BSTreeNode *pCurrent = que.front();
que.pop_front();
if(pCurrent->m_pleft != NULL)
{
nlast = pCurrent->m_pleft;
que.push_back(pCurrent->m_pleft);
}
if(pCurrent->m_pright != NULL)
{
nlast = pCurrent->m_pright;
que.push_back(pCurrent->m_pright);
}
if(pCurrent == last)
{
depthOfBSTree ++;
last = nlast;
}
}
}
void addBSTreeNode(BSTreeNode *&pCurrent, int value)
{
if(pCurrent == NULL)
{
BSTreeNode *pBSTree = new BSTreeNode();
pBSTree->m_nValue = value;
pBSTree->m_pleft = NULL;
pBSTree->m_pright = NULL;
pCurrent = pBSTree;
}
else
{
if((pCurrent->m_nValue) > value)
addBSTreeNode(pCurrent->m_pleft, value);
else if((pCurrent->m_nValue) < value)
addBSTreeNode(pCurrent->m_pright, value);
}
}