題目:輸入一棵二元樹的根結點,求該樹的深度。
從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
例如:輸入二元樹:
10
/ /
6 14
/ / /
4 12 16
輸出該樹的深度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
};
分析:這道題本質上還是考查二元樹的遍歷。
//coder:LEE 20120330
#include<iostream>
#include<CASSERT>
using namespace std;
struct SBinaryTreeNode
{
int m_nValue;
SBinaryTreeNode * m_pLeft;
SBinaryTreeNode * m_pRight;
};
void AddNode(SBinaryTreeNode *& root,int n)
{
if (!root)
{
root=(SBinaryTreeNode *)malloc(sizeof(SBinaryTreeNode ));
root->m_nValue=n;
root->m_pLeft=NULL;
root->m_pRight=NULL;
return;
}
if(n<root->m_nValue)
AddNode(root->m_pLeft,n);
else
AddNode(root->m_pRight,n);
}
void Traverse(SBinaryTreeNode * root)
{
if(!root)
return;
Traverse((root->m_pLeft));
cout<<root->m_nValue<<" ";
Traverse(root->m_pRight);
}
int ComputeDepthOfBiTree(SBinaryTreeNode * root)
{
if(root==NULL)
return 0;
int LeftDepth=ComputeDepthOfBiTree(root->m_pLeft);
int RightDepth=ComputeDepthOfBiTree(root->m_pRight);
return LeftDepth>RightDepth?LeftDepth+1:RightDepth+1;
}
int main()
{
SBinaryTreeNode * root=NULL;
AddNode(root,8);
AddNode(root,6);
AddNode(root,10);
AddNode(root,5);
AddNode(root,7);
AddNode(root,9);
AddNode(root,11);
AddNode(root,12);
Traverse(root);
cout<<endl;
cout<<ComputeDepthOfBiTree(root);
return 0;
}