递归方式判断二叉树是否完全二叉树
bool TreeComplete(TreeNode* root) {if (root != NULL) {if (root->left == NULL && root->right != NULL) {return false; // 左子树空}else if (root->left == NULL && root->right == NULL) {return true; // 左右子树空}else {return root->right == NULL ? TreeComplete(root->left) :TreeComplete(root->left) && TreeComplete(root->right);}}return false; // 空树
}
层序遍历方式(借助队列)判断二叉树是否完全二叉树
bool TreeComplete(TreeNode* root) {if (root != NULL) {Queue queue;Init(&queue);Push(&queue, root);while (!Empty(&queue)) {TreeNode* treeNode = Front(&queue);Pop(&queue);if (treeNode == NULL) {break;}Push(&queue, treeNode->left);Push(&queue, treeNode->right);}// 如果后面还有非NULL节点则不是完全二叉树while (!Empty(&queue)) {TreeNode* treeNode = Front(&queue);Pop(&queue);if (treeNode != NULL) {return false;}}return true;}return false;
}