Print a binary tree in a pretty way

后端 未结 15 1300
我寻月下人不归
我寻月下人不归 2020-11-28 22:15

Just wondering if I can get some tips on printing a pretty binary tree in the form of:

5
     10
          11
          7
               6
     3
          4         


        
15条回答
  •  野性不改
    2020-11-28 22:56

    Here's a little example for printing out an array based heap in tree form. It would need a little adjusting to the algorithm for bigger numbers. I just made a grid on paper and figured out what space index each node would be to look nice, then noticed there was a pattern to how many spaces each node needed based on its parent's number of spaces and the level of recursion as well as how tall the tree is. This solution goes a bit beyond just printing in level order and satisfies the "beauty" requirement.

    #include 
    #include 
    
    static const int g_TerminationNodeValue = -999;
    
    class HeapJ
    {
    public:
    HeapJ(int* pHeapArray, int numElements)
    {
        m_pHeapPointer = pHeapArray;
        m_numElements = numElements;
    
        m_treeHeight = GetTreeHeight(1);
    }
    
    void Print()
    {
        m_printVec.clear();
    
        int initialIndex = 0;
        for(int i=1; i m_printVec;
    
    int GetTreeHeight(int index)
    {
        const int value = m_pHeapPointer[index-1];
    
        if(value == g_TerminationNodeValue)
        {
            return -1;
        }
    
        const int childIndexLeft = 2*index;
        const int childIndexRight = childIndexLeft+1;
    
        int valLeft = 0;
        int valRight = 0;
    
        if(childIndexLeft <= m_numElements)
        {
            valLeft = GetTreeHeight(childIndexLeft);
        }
    
        if(childIndexRight <= m_numElements)
        {
            valRight = GetTreeHeight(childIndexRight);
        }
    
        return std::max(valLeft,valRight)+1;
    }
    
    void DoPrintHeap(int index, size_t recursionLevel, int numIndents)
    {
        const int value = m_pHeapPointer[index-1];
    
        if(value == g_TerminationNodeValue)
        {
            return;
        }
    
        if(m_printVec.size() == recursionLevel)
        {
            m_printVec.push_back(std::string(""));
        }
    
        const int numLoops = numIndents - (int)m_printVec[recursionLevel].size();
        for(int i=0; i

提交回复
热议问题