240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 4 | Leetcode 104. Maximum Depth of Binary Tree

题解

一道easy级别的题,不过适合用来练习BFS的模板套路。面对树结构,通常层级比较明显,如果是遇到图结构,有时则需要转化一下。

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        
        int depth = 0;
        
        queue<TreeNode*> q;
        q.push(root);
        
        while(!q.empty()) {
            int size = q.size();
            depth++;
            for(int i = 0; i < size; i++) {
                TreeNode* node = q.front();
                q.pop();
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
        }
        
        return depth;
    }
};
posted @ 2020-08-19 03:23  CasperWin  阅读(88)  评论(0编辑  收藏  举报