题目在线测试连接:二叉树的深度_牛客网 (nowcoder.com)
题目:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
题解:
int TreeDepth(TreeNode* pRoot)
{
int depth = 1; //假设当前节点存在,则深度为一
if(!pRoot) //如果当前节点不存在,返回0
return 0;
depth = max(depth, TreeDepth(pRoot->left) + 1); //当前节点存在,深度为max(1,左子树+1)
depth = max(depth, TreeDepth(pRoot->right) + 1); //当前节点存在,深度为max(depth,右子树+1)
return depth;
}
思路:分治,返回以子节点为根节点的完整子树的最大深度+1;
示意图:
TreeDepth(node_B)= 2