c++ - 这段代码有什么问题?它永远不会结束(二叉树的顶视图)
问题描述
问题陈述:打印二叉树的顶视图
我的方法:我维护一个队列,其中每个队列中都有一对 forroot->data
和horizontal distance(hd)
。我用队列中的 推根,hd
并将其添加到map
包含hd
和 的root->data
。然后我从队列中弹出。现在,如果弹出的根有任何孩子,我将它们插入队列,上述过程继续发生,直到队列不为空。
我的代码:-
void topView(Node * root) {
queue<pair<int, int>> q;
map<int, int> m;
q.push({root->data, 0});
while(q.empty() == false){
int node_val = q.front().first;
int hd = q.front().second;
m[hd] =node_val;
q.pop();
if(root->left){
int hdl = hd -1;
q.push({root->left->data, hdl});
}
if(root->right){
int hdr = hd + 1;
q.push({root->right->data, hdr});
}
}
for(auto i=m.begin();i!=m.end();i++)
{
cout<<i->second<<" ";
}
}
**错误:**超过时间限制(即代码不会停止运行)
**注意**:另外,我发现我无法在我的代码中正确更新“水平距离(hd)”每个节点。而且我不能将`hd`添加为Node类的成员,所以我必须将它放入这个函数本身并且我无法找到一种方法来做到这一点。(`hdl`和`hdr`)
请帮助并对代码进行一些更正。
先感谢您。
解决方案
您的代码中有两个问题。一种是您只将节点值存储在队列中,而不是节点指针。所以你的遍历条件
if(root->left)
仅检查根节点的子节点。这会导致无限循环,因为我们没有遍历根节点。第二个问题是即使我们正确遍历,顶视图逻辑也没有正确使用地图。
m[hd] = node_val
由于这是覆盖每个高清,这将为您提供底部视图。我们希望这里的每个 hd 第一次出现。我已经更新了代码。
void topView(Node * root) {
queue<pair<Node*, int>> q;
map<int, int> m;
q.push({root->data, 0});
while(q.empty() == false){
Node* current_node = q.front().first;
int node_val = current_node->data;
int hd = q.front().second;
if(m.find(hd) == m.end())
m[hd] =node_val;
q.pop();
if(current_node->left){
int hdl = hd -1;
q.push({current_node->left, hdl});
}
if(current_node->right){
int hdr = hd + 1;
q.push({current_node->right, hdr});
}
}
for(auto i=m.begin();i!=m.end();i++)
{
cout<<i->second<<" ";
}
}
推荐阅读
- delphi - FMX:如何结合使用 ClearRect 和 IntersectClipRect?
- windows - 在不指定网络地址的情况下无法通过 Firebird 别名连接到本地数据库
- wmi - WMI 查询的不同结果取决于用户帐户?
- neo4j - Neo4j 中作为列表或数组的属性
- css - 在反应中单击按钮时在多个按钮样式之间切换
- r - 基于向量提取列,如何以正确的顺序获取它?
- rust - 如何更改动态调度/特征对象的数据指针?
- python - 修改 python 中预先存在的 float 类以包含自定义圆形函数
- excel - 从主文件到多个文件的 VBA 更新链接
- r - aws.s3 R 包 - 用于浏览器显示的 put() 图像