How do I print out a tree structure?

前端 未结 8 1540
予麋鹿
予麋鹿 2020-11-27 12:42

I\'m trying to improve performance in our app. I\'ve got performance information in the form of a tree of calls, with the following node class:

public class         


        
相关标签:
8条回答
  • 2020-11-27 13:30

    i am using the following method to print a BST

    private void print(Node root, String prefix) {
        if (root == null) {
        System.out.println(prefix + "+- <null>");
        return;
        }
    
        System.out.println(prefix + "+- " + root);
        print(root.left, prefix + "|  ");
        print(root.right, prefix + "|  ");
    }
    

    Following is the output.

    +- 43(l:0, d:1)
    |  +- 32(l:1, d:3)
    |  |  +- 10(l:2, d:0)
    |  |  |  +- <null>
    |  |  |  +- <null>
    |  |  +- 40(l:2, d:2)
    |  |  |  +- <null>
    |  |  |  +- 41(l:3, d:0)
    |  |  |  |  +- <null>
    |  |  |  |  +- <null>
    |  +- 75(l:1, d:5)
    |  |  +- 60(l:2, d:1)
    |  |  |  +- <null>
    |  |  |  +- 73(l:3, d:0)
    |  |  |  |  +- <null>
    |  |  |  |  +- <null>
    |  |  +- 100(l:2, d:4)
    |  |  |  +- 80(l:3, d:3)
    |  |  |  |  +- 79(l:4, d:2)
    |  |  |  |  |  +- 78(l:5, d:1)
    |  |  |  |  |  |  +- 76(l:6, d:0)
    |  |  |  |  |  |  |  +- <null>
    |  |  |  |  |  |  |  +- <null>
    |  |  |  |  |  |  +- <null>
    |  |  |  |  |  +- <null>
    |  |  |  |  +- <null>
    |  |  |  +- <null>
    
    0 讨论(0)
  • 2020-11-27 13:35

    Here is a variation on the (currently-accepted) answer by @Will. The changes are:

    1. This uses Unicode symbols instead of ASCII for a more pleasing appearance.
    2. The root element is not indented.
    3. The last child of a group has a 'blank' line added after it (makes it easier to visually parse).

    Presented as pseudo-code for easier consumption outside of C++:

    def printHierarchy( item, indent )
      kids = findChildren(item)  # get an iterable collection
      labl = label(item)         # the printed version of the item
      last = isLastSibling(item) # is this the last child of its parent?
      root = isRoot(item)        # is this the very first item in the tree?
    
      if root then
        print( labl )
      else
        # Unicode char U+2514 or U+251C followed by U+2574
        print( indent + (last ? '└╴' : '├╴') + labl )
    
        if last and isEmpty(kids) then
          # add a blank line after the last child
          print( indent ) 
        end
    
        # Space or U+2502 followed by space
        indent = indent + (last ? '  ' : '│ ')
      end
    
      foreach child in kids do
        printHierarchy( child, indent )
      end
    end
    
    printHierarchy( root, "" )
    

    Sample result:

    Body
    ├╴PaintBlack
    ├╴CarPaint
    ├╴Black_Material
    ├╴PaintBlue
    ├╴Logo
    │ └╴Image
    │
    ├╴Chrome
    ├╴Plastic
    ├╴Aluminum
    │ └╴Image
    │
    └╴FabricDark
    
    0 讨论(0)
提交回复
热议问题