程序使用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<< "给定树的俯视图:" << 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;
}

输出结果

给定树的俯视图:
23 11 35 68