//class TreeNode {
// public:
// int value;
// TreeNode* left;
// TreeNode* right;
// TreeNode(int v) : value(v), left(NULL), right(NULL) {}
//};
class Solution {
public:
bool isCompleted(TreeNode* root) {
// write your solution here
if (root == nullptr || (root->left == nullptr && root->right == nullptr)) return true;
queue< pair<TreeNode*, int> > q;
TreeNode * new_node = root; // current node
int new_level = 0; // initial level
q.push(make_pair(new_node, new_level));
int curr_level = 0;
int num_nodes_curr_level = 0;
while(!q.empty()){
new_node = q.front().first;
new_level = q.front().second;
// operate on child nodes
if (new_node->left != nullptr) q.push(make_pair(new_node->left, new_level+1));
if (new_node->right != nullptr) q.push(make_pair(new_node->right, new_level+1));
if (new_level == curr_level)
num_nodes_curr_level++;
else{
// we finished a level. Check if this level is complete.
if (num_nodes_curr_level != pow(2, curr_level))
return false;
else{
curr_level = new_level;
num_nodes_curr_level++;
}
}
}
return true;
}
};
Not sure if it's correct...
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.