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!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.