题目
代码(8.17 首刷看解析)
这个方式更简单,将nil
也加入进去,只能有一个nil
,如果后面再出现nil就直接false了
func isCompleteTree(root *TreeNode) bool {
q := []*TreeNode{root}
flag := false
for len(q) > 0 {
front := q[0]
q = q[1:]
if front == nil {
flag = true
continue
}
if flag == true {
return false
}
q = append(q, front.Left)
q = append(q, front.Right)
}
return true
}
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
bool flag = false;
while(!q.empty()) {
auto front = q.front();
q.pop();
if(!front->left && front->right)
return false;
if(flag && (front->left || front->right))
return false;
if((!front->left && !front->right) || (front->left && !front->right))
flag = true;
if(front->left) q.push(front->left);
if(front->right) q.push(front->right);
}
return true;
}
};
代码(10.1 二刷自解)
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
bool flag = false;
while(!q.empty()) {
int sz = q.size();
for(int i = 0; i < sz; i++) {
auto front = q.front();
q.pop();
if(flag && (front->left || front->right)) return false;
if(front->left) {
if(flag)
return false;
q.push(front->left);
} else
flag = true;
if(front->right) {
if(flag)
return false;
q.push(front->right);
}
else flag = true;
}
}
return true;
}
};