以树格式打印堆阵列 [英] Print heap array in tree format

查看:126
本文介绍了以树格式打印堆阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在尝试实现一个算法以树格式输出一个堆数组。对于
实例,如果我有一个数组像A [10,6,8,2,4,3,6,0,1,3,2,2,1,0,2]我想输出be:

So I've been trying to implement an algorithm to output a heap array in tree format. For instance if I have an array like A[10,6,8,2,4,3,6,0,1,3,2,2,1,0,2] I would like the output to be:

10-----6-----2-----0
    |     |     |--1
    |     |--4-----3
    |           |--2   
    |--8-----3-----2
          |     |--1
          |--6-----0
                |--2


$ b

Update: Solved my question, I made an answer with the code for those interested.

推荐答案

更新:解决我的问题,最终实施。格式化数字长度。

Here is the final implementation. Formatting scales with number length.

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>

std::string do_padding (unsigned index, unsigned mlength){
  std::string padding;
  if (int((index-1)/2) != 0){
    return (int((index-1)/2) % 2 == 0) ?
    (do_padding(int((index-1)/2),mlength) + std::string(mlength+4,' ') + " ")  :
    (do_padding(int((index-1)/2),mlength) + std::string(mlength+3,' ') + " |") ;
  }
  return padding;
}


void printer (std::vector<int> const & tree, unsigned index, unsigned mlength){
  auto last = tree.size() - 1 ;
  auto  left = 2 * index + 1 ;
  auto  right = 2 * index + 2 ;
  std::cout << " " << tree[index] << " ";
  if (left <= last){
    auto llength = std::to_string(tree[left]).size();
    std::cout << "---" << std::string(mlength - llength,'-');
    printer(tree,left,mlength);
    if (right <= last) {
      auto rlength = std::to_string(tree[right]).size();
      std::cout << "\n" << do_padding(right,mlength) << std::string(mlength+ 3,' ') << " | ";
      std::cout << "\n" << do_padding(right,mlength) << std::string(mlength+ 3,' ') << " └" <<
      std::string(mlength - rlength,'-');
      printer(tree,right,mlength);
    }
  }
}


void print_tree (std::vector<int> & tree){
  unsigned mlength = 0;
  for (int & element : tree){
    auto clength = std::to_string(element).size();
    if (clength > mlength) {
      mlength = std::to_string(element).size();
    }
  }
  std::cout <<  std::string(mlength- std::to_string(tree[0]).size(),' ');
  printer(tree,0,mlength);
}

int main() {
  std::vector<int> test;
  for(auto i =0; i<50; ++i){
    test.push_back(rand() % 1000 + 1);
  }
  std::make_heap(test.begin(),test.end());
  std::cout << "\n";
  print_tree(test);
}

这篇关于以树格式打印堆阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆