[LeetCode]104. 二叉树的最大深度 原创
题目来源 LeetCode
算法标签 二叉树,bfs,dfs
题目描述

思路
dfs手动+1表示层数
bfs利用队列模仿一层一层累加
AC代码
dfs
/**
 * 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:
    int maxDepth(TreeNode* root) {
        if(root==nullptr)return 0;
        return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};
bfs
/**
 * 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:
    int maxDepth(TreeNode* root) {
        queue<TreeNode*>q;
        
        int ans=0;
        if(root!=nullptr)q.push(root);
        while(q.size())
        {
            for(int i=q.size()-1;i>=0;i--)
            {
                auto t = q.front();
                q.pop();
                if(t->left)q.push(t->left);
                if(t->right)q.push(t->right);
            }
            ans++;
        }
        return ans;
    }
};
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号