题目:36. 二叉树的深度
知识点:二叉树
题目描述:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题思路:
思路简单,没啥好说的,一行代码搞定。
代码:
//解法一(自研):
int TreeDepth(TreeNode* pRoot)
{
return pRoot == nullptr ? 0 : max(TreeDepth(pRoot->left), TreeDepth(pRoot->right))+1;
}
//解法二(剑指Offer 思路同上):
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);
}