使用 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

更新於: 01-11-2019

149 檢視

開啟你的 職業生涯

完成課程即可獲得認證資格

開始學習
廣告
© . All rights reserved.