[leetcode]958. Check Completeness of a Binary Tree

[leetcode]958. Check Completeness of a Binary Tree


Analysis

药不能停—— [每天刷题并不难0.0]

Given a binary tree, determine if it is a complete binary tree.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
在这里插入图片描述

Explanation:

用BFS遍历二叉树,当遇到空节点时,如果队列中还有未遍历的节点则该二叉树不完整。

Implement

/**
 * 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:
    bool isCompleteTree(TreeNode* root) {
        queue<TreeNode*> mq;
        bool pre = true;
        mq.push(root);
        while(!mq.empty()){
            TreeNode* node = mq.front();
            mq.pop();
            if(!node)
                pre = false;
            else{
                if(!pre)
                    return false;
                mq.push(node->left);
                mq.push(node->right);
            }
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/85319247
今日推荐