Print binary tree in a pretty way using c++

前端 未结 4 1492
广开言路
广开言路 2021-02-01 09:03

I am a \"bit\" lost trying to print a binary tree like below in c++:

            8
           / \\
          /   \\
         /     \\
        5       10
       /         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 10:01

    I wrote arbitrary tree pretty printer as a part of C++ algorithms self-education.

    The approach is following.

    • From each tree node printable node with stringified original node value and absolute position in the line composed.
    • Sibling printable nodes grouped. Each sibling group contains list of nodes and pointer to parent printable node.
    • Sibling groups grouped to lines, each line represents original tree level.

    Next, printable nodes position are calculated.

    • Lines iterated through skipping first one.
    • Siblings in the line iterated, each sibling group moved to its parent node center if the center is further then the middle of the group. It moves even further if intersected with previous siblings group. Parent node moved to the middle of the children nodes if the middle is further than parent center. Nodes following parent node are shifted if intersected with shifted parent node.
    • Previous step repeated for siblings group parent siblings group recursively.

    For the last step lines iterated once again to be written to the provided output stream, filling with spaces offsets according to the calculated nodes positions.

    Unix box-drawing symbols are used to draw lines. Not sure if they will be printed correctly in Windows cmd, maybe they should be replaced by their DOS counterparts for Windows.

                                1
          ┌────────────┬────────┴────────────────────┐
         11           12                            13
     ┌────┼────┐    ┌──┴─┐                 ┌─────────┴────┬────┐
    111  112  113  121  122               131            132  133
                   ┌─────┼─────┐     ┌─────┼─────┐     ┌──┴──┐
                 1221  1222  1223  1311  1312  1313  1321  1322
    
    

    Unit tests with usage samples

提交回复
热议问题