/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
int res = 0;
int tmp = 0;
curision(pRoot, res, tmp);
return res;
}
private:
void curision(TreeNode *root, int &res, int &tmp) {
if (root == nullptr) {
res = std::max(res, tmp);
return ;
}
++tmp;
curision(root->left, res, tmp);
curision(root->right, res, tmp);
// 回溯
--tmp;
}
};
简洁
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
if (pRoot == nullptr) {
return 0;
}
// 1是当前节点,加上左右子树中最大的那部分
return 1 + std::max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
}
};