코테준비 - Maximum Depth of Binary Tree

정상화·2023년 2월 26일

LeetCode

목록 보기
101/222

Maximum Depth of Binary Tree

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == nullptr) return 0;
        int depth = 0;

        queue<TreeNode*> Q;
        Q.push(root);
        while (!Q.empty()) {
            depth++;
            int qLen = Q.size();
            for (int i = 0; i < qLen; i++) {
                auto node = Q.front();
                Q.pop();
                if (node->left != nullptr) {
                    Q.push(node->left);
                }
                if (node->right != nullptr) {
                    Q.push(node->right);
                }
            }
        }
        return depth;
    }
};
profile
백엔드 희망

0개의 댓글