题目:958. 二叉树的完全性检验 - 力扣(LeetCode)
题解
类似与判定搜索二叉树中序遍历有序,判定完全二叉树层序遍历有序且以固定差为1递增。
代码
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
// 层序遍历
queue<TreeNode*> q;
q.push(root);
// 在结点入队列时,同时将其序号也入队
queue<long> indexs;
indexs.push(0);
long prev = -1;
while(!q.empty())
{
int size = q.size();
while(size)
{
TreeNode* cur = q.front();
int index = indexs.front();
q.pop(); indexs.pop(); size--;
if(prev == -1) prev = index;
else
{
if(prev + 1 == index) prev = index;
else return false;
}
if(cur->left)
{
q.push(cur->left);
indexs.push(index * 2 + 1);
}
if(cur->right)
{
q.push(cur->right);
indexs.push(index * 2 + 2);
}
}
}
return true;
}
};
题目:662. 二叉树最大宽度 - 力扣(LeetCode)
题解
同上一题,利用序号,在每一层遍历时,只需要最右序号-最左序号+1就得到该层的宽度了。
代码
注意:因为二叉树深度可能比较深,则序号比较大,用unsigned int 存储才能存下。
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
queue<TreeNode*> q;
queue<unsigned int> index;
q.push(root);
index.push(0);
unsigned int wideMax = 1; // 初始化为1 至少有一个根节点 宽度是1
while(!q.empty())
{
int size = q.size();
unsigned int left = index.front();
unsigned int right = left;
while(size)
{
TreeNode* cur = q.front();
unsigned int num = index.front();
q.pop(); index.pop(); size--;
right = num;
if(cur->left)
{
q.push(cur->left);
index.push(num * 2 + 1);
}
if(cur->right)
{
q.push(cur->right);
index.push(num * 2 + 2);
}
}
wideMax = max(wideMax, right - left + 1);
}
return wideMax;
}
};