题目:输入一棵二叉树的根结点,求该树的深度。
struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}
- 如果一棵树只有一个节点,那么它的深度为1.如果根节点只有左子树而没有右子树,那么树的深度应该是其左子树的深度加1;同样,如果根节点只有右子树而没有左子树,那么树的深度应该是其右子树的深度加1.如果既有右子树又有左子树,那么该树的深度就是其左右子树深度的较大值再加1.
int TreeDepth(const BinaryTreeNode* pRoot)
{
if(pRoot == nullptr)
return 0;
int nLeft = TreeDepth(pRoot->m_pLeft);
int nRight = TreeDepth(pRoot->m_pRight);
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}