使用 C++ 打印二叉树顶部视图中的节点的程序
在本教程中,我们将讨论一个程序,该程序用于打印给定二叉树顶部视图中显示的所有节点。
对于特定的二叉树,如果一个节点在其水平距离内是第一个节点,那么该节点出现在其顶部视图中。节点 x 的左节点的水平距离为 x-1,节点 x 的右节点的水平距离为 x+1。
为了解决此问题,我们将进行层序遍历,以便在该层次的其他节点之前获取特定层次的最顶层节点。此外,我们将使用哈希检查选定的节点是否在顶部视图中可见。
示例
#include <iostream>
#include<queue>
#include<map>
using namespace std;
struct Node{
Node * left;
Node* right;
int h_dist;
int data;
};
Node* create_node(int key){
Node* node=new Node();
node->left = node->right = NULL;
node->data=key;
return node;
}
void print_topview(Node* root){
if(root==NULL)
return;
queue<Node*>q;
map<int,int> m;
int h_dist=0;
root->h_dist=h_dist;
q.push(root);
cout<< "Top View for the given tree:" << endl;
while(q.size()){
h_dist=root->h_dist;
if(m.count(h_dist)==0)
m[h_dist]=root->data;
if(root->left){
root->left->h_dist=h_dist-1;
q.push(root->left);
}
if(root->right){
root->right->h_dist=h_dist+1;
q.push(root->right);
}
q.pop();
root=q.front();
}
for(auto i=m.begin();i!=m.end();i++){
cout<<i->second<< " ";
}
}
int main(){
Node* root = create_node(11);
root->left = create_node(23);
root->right = create_node(35);
root->left->right = create_node(47);
root->left->right->right = create_node(59);
root->left->right->right->right = create_node(68);
print_topview(root);
return 0;
}输出
Top View for the given tree: 23 11 35 68
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP