目前接触到的层序遍历有两种,一是只存非空结点,二是空结点和非空结点都存
区别:
第一种情况,不存,涉及提取队列长度queue.size(),如果存空结点会影响实际情况
第二种情况,存,涉及两个树的比较,所以位置需要一一对应,空结点对空结点
一是:判断是否为空结点,非空结点才存到队列中,出队是的结点都是非空结点,队列中的结点都是实实在在存在的结点,没有空结点
例:《力扣104. 二叉树的最大深度(递归DFS、迭代BFS&DFS)》
https://blog.csdn.net/qq_35683407/article/details/105609130
int maxDepthiteration(TreeNode* root)
{
//鲁棒性,如果为空树,直接返回0层
if (root == nullptr)return 0;
//当前层的个数curcount,记录有几个结点,初始化为零
int curcount = 0;
//当前树的深度depth,记录有几层,初始化为零
int depth = 0;
//下一层的个数nextcount,下一层有几个结点,初始化为1(代表根节点)
int nextcount = 1;
queue<TreeNode*>que;
que.push(root);
while (!que.empty())
{
TreeNode* temp = que.front();
que.pop();
//非空结点,层序遍历
cout << temp->val << '\t' << depth << '\n';
curcount++;
//叶结点,跳过
if (temp->left)que.push(temp->left);
if (temp->right)que.push(temp->right);
//当前层遍历的结点等于nextcount时,说明要换一层了
//depth加一,curcount初始化为零,nextcount为当前队列的个数
if (curcount == nextcount)
{
depth++;
curcount = 0;
nextcount = que.size();
}
}
return depth;
}
二是:不管是否空结点,先将结点存到队列中,出队时再判断是否为空结点
例一:《力扣100. 相同的树(递归、迭代)》
https://blog.csdn.net/qq_35683407/article/details/105592504
bool isSameTreeiteration(TreeNode* p, TreeNode* q)
{
//创建两个队列,一个压p,一个压q
queue<TreeNode*>euep;
euep.push(p);
queue<TreeNode*>eueq;
eueq.push(q);
//只要队列中有指针,就一直比较
while (!euep.empty() && !eueq.empty())
{
//取出各自队列中第一个指针
TreeNode* t1 = euep.front(); euep.pop();
TreeNode* t2 = eueq.front(); eueq.pop();
//如果他们两个都是空指针,说明到头了,不用比较了,继续下一个循环
//相当于递归终止条件
if (t1==nullptr && t2==nullptr)
{
continue;
}
//比较值相等的条件,首先是当下的p与q结点存在(判断是否为空指针),接着p与q结点值是否相等(判断值是否相等)
//如果满足条件,继续比较左子树和右子树,把各自左子树和右子树压入队列
if ((t1 != nullptr && t2 != nullptr)&& (t1->val==t2->val))
{
euep.push(t1->left); euep.push(t1->right);
eueq.push(t2->left); eueq.push(t2->right);
continue;
}
//只要条件有一项不满足,都返回false
else
{
return false;
}
}
return true;
}
例二:《力扣101. 对称二叉树(递归、迭代)》
https://blog.csdn.net/qq_35683407/article/details/105606179
bool isSymmetriciteration(TreeNode* root)
{
//从左到右
queue<TreeNode*> que1;
que1.push(root);
//从右到左
queue<TreeNode*> que2;
que2.push(root);
while (!que1.empty() && !que2.empty())
{
TreeNode* t1 = que1.front(); que1.pop();
TreeNode* t2 = que2.front(); que2.pop();
//同时为空,则是对称为空
if (t1 == NULL && t2 == NULL)continue;
//一个有一个没有,则不对称
if (t1 == NULL || t2 == NULL)return false;
if (t1->val != t2->val)return false;
//从左到右,先放左再放右
que1.push(t1->left); que1.push(t1->right);
//从右到左,先放右再放左
que2.push(t2->right); que2.push(t2->left);
}
return true;
}