剑指 Offer 55 - I. 二叉树的深度 - 力扣(LeetCode)
层次遍历即可
class Solution { public: int maxDepth(TreeNode* root) { if(!root) return 0; queue<TreeNode*> q; q.push(root); int cnt = 0; while(!q.empty()){ int n = q.size(); for(int i = 0; i < n; ++i){ auto cur = q.front(); q.pop(); if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); } ++cnt; } return cnt; } };dfs也可:
class Solution { public: int maxDepth(TreeNode* root) { if(!root) return 0; return 1 + max(maxDepth(root->left), maxDepth(root->right)); } };