题目:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解析:二叉树的遍历 想法是递归
分第三种情况
1)当遇到空节点的时候 则更新max_depth的值
2)递归遍历左节点
3)递归遍历右节点
注意事项 max_depth 记得传引用或者使用全局变量
代码:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void tryTree(TreeNode* treeRoot, int &max_depth, int cur_depth)
{
if (treeRoot == NULL)
{
if (max_depth < cur_depth) max_depth = cur_depth;
return;
}
tryTree(treeRoot->left, max_depth, cur_depth + 1);
tryTree(treeRoot->right, max_depth, cur_depth + 1);
}
int TreeDepth(TreeNode* pRoot)
{
if (pRoot == nullptr) return 0;
int max_depth = -1;
TreeNode* treeRoot = pRoot;
tryTree(treeRoot, max_depth, 0);
return max_depth;
}
};