使用迭代法的话,使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数,和层序遍历的方式极其吻合。
在二叉树中,一层一层的来遍历二叉树,记录一下遍历的层数就是二叉树的深度。
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> q;
if(root) q.push(root);
int nums = 0;
while(!q.empty()){
int size = q.size();
for(int i = 0; i < size; i++){
TreeNode* cur = q.front();
q.pop();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
nums++;
}
return nums;
}
};
方法 1:标准 DFS 递归(后序遍历)
思路:计算左子树和右子树的深度,取较大值并 +1
(当前层深度)。
class Solution {
public:
int maxDepth(TreeNode* root) {
int level = 0;
if(root == nullptr) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right) + 1;
}
};
方法 2:DFS + 传当前深度(前序遍历)
思路:在递归时维护当前深度,并更新全局最大深度。
class Solution {
private:
int max = 0;
void traverse(TreeNode* cur, int level){
if(cur == nullptr) return;
if(level > max) max = level;
if(cur->left) traverse(cur->left, level+1);
if(cur->right) traverse(cur->right, level+1);
}
public:
int maxDepth(TreeNode* root) {
traverse(root, 1);
return root ? max : 0;
}
};