这个题就简单了,首先涉及到二叉树,必须想到递归
涉及到递归的话,两个东西非常重要:递归式和终止条件
f(root) = max {f(root->left), f(foot->right) } + 1
这个递归式应该知道。
终止条件也很简单 root == NULL
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { if (root == NULL) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };