題目:輸入一棵二元樹的根結點,求該樹的深度。
從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
例如:輸入二元樹:
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);
}
}