Last active
December 30, 2018 01:50
-
-
Save kanrourou/a33eb34156f16811387c33cfa3cdc29a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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<TreeNode*> q; | |
int depth = 0; | |
q.push(root); | |
while(q.size()) | |
{ | |
int len = q.size(); | |
bool hasNull = false; | |
if((1 << depth) != len) | |
{ | |
//verify if it is the last laryer | |
for(int i = 0; i < len; ++i) | |
{ | |
auto node = q.front(); | |
q.pop(); | |
if(node->left || node->right)return false; | |
} | |
} | |
else | |
{ | |
//verify all nodes in next level are posed as left as possible | |
for(int i = 0; i < len; ++i) | |
{ | |
auto node = q.front(); | |
q.pop(); | |
if(node->left){ if(hasNull)return false; q.push(node->left); } | |
else hasNull = true; | |
if(node->right){ if(hasNull)return false; q.push(node->right); } | |
else hasNull = true; | |
} | |
} | |
++depth; | |
} | |
return true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment