很明显能列出递归方程 depth(i)=max(depth(left),depth(right))+1;
根据递归方程递归编写代码,时间复杂度为O(n);
int find(TreeNode* root)
{
int depth = 0;;
int maxleft = 1, maxright = 1;
if (root == NULL) return depth;
else depth++;
if (root->left != NULL) maxleft = find(root->left) + depth;
if (root->right != NULL)maxright = find(root->right) + depth;
return max(maxleft, maxright);
}
int TreeDepth(TreeNode* pRoot)
{
if (pRoot == NULL) return 0;
return find(pRoot);
}