52.二元树的深度。
题目:输入一棵二元树的根结点,求该树的深度。
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为
树的深度。
例如:输入二元树:
10
/ \
6 14
/ / \
4 12 16
输出该树的深度3。
namespace MS100P_52
{
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
};
int depth(SBinaryTreeNode* root)
{
if (root == NULL)
return 0;
int leftDepth, rightDepth;
leftDepth = depth(root->m_pLeft);
rightDepth = depth(root->m_pRight);
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
}