Print a binary tree in a pretty way

后端 未结 15 1333
我寻月下人不归
我寻月下人不归 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:41

    Do an in-order traversal, descending to children before moving to siblings. At each level, that is when you descent to a child, increase the indent. After each node you output, print a newline.

    Some psuedocode. Call Print with the root of your tree.

    void PrintNode(int indent, Node* node)
    {
        while (--indent >= 0)
            std::cout << " ";
        std::cout << node->value() << "\n";
    }
    
    void PrintNodeChildren(int indent, Node* node)
    {
        for (int child = 0; child < node->ChildCount(); ++child)
        {
            Node* childNode = node->GetChild(child);
            PrintNode(indent, childNode);
            PrintNodeChildren(indent + 1, childNode);
        }
    }
    
    void Print(Node* root)
    {
       int indent = 0;
       PrintNode(indent, root);
       PrintNodeChildren(indent + 1, root);  
    }
    

提交回复
热议问题