/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root, int d) {
if (root->left) dfs(root->left, d+1);
if (root->right) dfs(root->right, d+1);
ans = max(ans, d);
}
int treeDepth(TreeNode* root) {
if (root == NULL) return 0;
ans = 0;
dfs(root, 1);
return ans;
}
private:
int ans;
};
// 一行代码解决 class Solution { public: int treeDepth(TreeNode* root) { return root?1+max(treeDepth(root->left),treeDepth(root->right)):0; } };
牛逼啊哥