简体   繁体   中英

printing the order of a binary search tree by passing a var to a recursive function

I am building a binary search tree for a class and have the insertion working just fine, my only problem is displaying a number next to each item I am printing such as

  1. Steven $80
  2. Joe $10
  3. John $3

my print function is recursive and prints in reverse order with the large items first(right tree), I was thinking I would pass an int to the function initialized to 0 and increment for each print so that it would read 1,2,3... but the recursive nature of the function calling itself is giving me some problems. Any help or suggestions would be greatly appreciated.

void CTree::PrintTree(TreeNode*& tree, int count){ 

    count++;

    if (tree != NULL){         
        PrintTree(tree->right, count);  // Print right subtree.
        cout << count <<" " << tree->name << " $" << tree->bribe << endl; //print node
        PrintTree(tree->left, count);   // Print left subtree.
    }
} 
void CTree::PrintTree(TreeNode*& tree, Bool isRoot=true){ 

    static int count=0;
    if(isRoot) count=0; else count++;

    if (tree != NULL){         
        PrintTree(tree->right, false);  // Print right subtree.
        cout << count <<" " << tree->name << " $" << tree->bribe << endl; //print node
        PrintTree(tree->left, false);   // Print left subtree.
    }
} 

call it with just PrintTree(tree) or PrintTree(tree,true)

Another approach (non-static) would be encapsulate int in an class and provide methods for add and get. Use object of this class as passing parameter, add() before printing and get while printing.

In Java,

static class Counter
{
int count;
void add(){
    count++;
}

int get(){
    return count;
 }
 }

Now while printing:

void PrintTree(TreeNode tree, Counter counter){
    if(tree != null){
        PrintTree(tree.right, counter);
        counter.add();
        System.out.println(counter.get()+ " " + tree.name + " $" + tree.bribe);
        //cout << count <<" " << tree->name << " $" << tree->bribe << endl; //print node
        PrintTree(tree.left, counter);
     }
 }

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.

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