我有一个打印树的内容的方法:
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);
}
试试吧!
关于c++ - 树内容的格式化输出——先序遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13875010/