跳转至

二叉树的完全性检验⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isCompleteTree(TreeNode* root) {
        if (!root) return true;

        queue<TreeNode*> q;
        q.push(root);
        bool isNull = false;

        while (!q.empty()) {
            auto node = q.front(); q.pop();
            if (!node) {
                isNull = true;
            } else {
                if (isNull) return false;
                q.push(node->left); q.push(node->right);
            }
        }

        return true;
    }
};