繁体   English   中英

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

[英]Formatting output of tree contents - Preorder traversal

我有一种打印树内容的方法:

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

我的树的内容正在正确读出,但是我想格式化树以使其看起来更好。 现在,对于一棵树:

    c
   / \
  b   k
 /   / \
a   d   m

内容打印:

c
b
a
k
d
m

但我想添加一些缩进,使其显示为:

c
    b
        a
    k
        d
        m

格式为:

Root
    Left 
        LeftLeft
        LeftRight
    Right
        RightLeft
        RightRight

etc....

我只是对递归有点迷路。 谢谢!

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);
}  

试试看!!

暂无
暂无

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

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