简体   繁体   English

格式化树内容的输出-预遍遍

[英]Formatting output of tree contents - Preorder traversal

I have a method to print the contents of a tree: 我有一种打印树内容的方法:

void RedBlackTree::printPreorder(RedBlackNode *root){
    if(root == NULL) 
        return;
    cout << root->data << endl;
    printInorder(root->left);
    printInorder(root->right);
}

The contents of my tree are reading out correctly, but I want to format the tree so that it looks nicer. 我的树的内容正在正确读出,但是我想格式化树以使其看起来更好。 Right now, for a tree: 现在,对于一棵树:

    c
   / \
  b   k
 /   / \
a   d   m

The contents print: 内容打印:

c
b
a
k
d
m

But I'd like to add some indentation, so that it reads: 但我想添加一些缩进,使其显示为:

c
    b
        a
    k
        d
        m

The format would be: 格式为:

Root
    Left 
        LeftLeft
        LeftRight
    Right
        RightLeft
        RightRight

etc....

I'm just getting a bit lost with the recursion. 我只是对递归有点迷路。 Thanks! 谢谢!

void RedBlackTree::printPreorder(RedBlackNode *root, int depth){
    if(root == NULL) 
        return;
    for(int i=0; i<=depth; i++)
      cout <<" ";

    depth++;
    cout << root->data << endl;
    printInorder(root->left, depth);
    printInorder(root->right, depth);
}  

Give it a try!! 试试看!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM