Check Completeness of a Binary Tree Solutions in C++
Number 958
Difficulty Medium
Acceptance 52.1%
Link LeetCode
Other languages Python
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/check-completeness-of-a-binary-tree//// Author : liuyubobobo/// Time : 2018-12-15#include <iostream>#include <vector>using namespace std;/// Recursion/// Time Complexity: O(n+)/// Space Complexity: O(h)/// 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) {if(!root) return true;TreeNode* cur = root;int left = 0;while(cur)left ++, cur = cur->left;cur = root;int right = 0;while(cur)right ++, cur = cur->right;if(left < right) return false;if(left == right)return isFullTree(root->left, left - 1) && isFullTree(root->right, right - 1);if(left - right > 1) return false;return (isFullTree(root->left, left - 1) && isCompleteTree(root->right)) ||(isCompleteTree(root->left) && isFullTree(root->right, right - 1));}private:bool isFullTree(TreeNode* root, int depth){if(!root)return depth == 0;return isFullTree(root->left, depth - 1) && isFullTree(root->right, depth - 1);}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/check-completeness-of-a-binary-tree//// Author : liuyubobobo/// Time : 2018-12-15#include <iostream>#include <vector>#include <queue>using namespace std;/// BFS/// Time Complexity: O(n)/// Space Complexity: O(n)/// 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) {if(!root) return true;queue<pair<TreeNode*, int>> queue;queue.push(make_pair(root, 1));int max_index = -1, sz = 0;while(!queue.empty()){TreeNode* node = queue.front().first;int index = queue.front().second;queue.pop();sz ++;max_index = max(max_index, index);if(node->left)queue.push(make_pair(node->left, 2 * index));if(node->right)queue.push(make_pair(node->right, 2 * index + 1));}return sz == max_index;}};int main() {return 0;}