输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题思路
- 回溯法
上代码(C++很香)
回溯法,每次可以向左和向右走,最后统计最大的深度
int maxD = 0;
void dfs(TreeNode* pNode, int depth){
// 叶子节点
if(pNode->left == nullptr && pNode->right == nullptr){
if(depth > maxD)
maxD = depth;
return ;
}
if(pNode->left != nullptr)
dfs(pNode->left, depth + 1);
if(pNode->right != nullptr)
dfs(pNode->right, depth + 1);
}
int TreeDepth(TreeNode* pRoot){
if(pRoot == nullptr)
return 0;
dfs(pRoot, 1);
return maxD;
}