通过将var传递给递归函数来打印二叉搜索树的顺序

时间:2011-12-08 05:27:17

标签: c++ recursion printing tree binary-tree

我正在为一个类构建二进制搜索树,并且插入工作正常,我唯一的问题是在我打印的每个项目旁边显示一个数字,例如

  1. 史蒂文$ 80
  2. Joe $ 10
  3. John $ 3
  4. 我的打印功能是递归的,并且以相反的顺序打印,首先是大项目(右侧树),我想我会将一个int传递给初始化为0的函数,并为每个打印增加,以便它将读取1,2 ,3 ......但函数调用本身的递归性质给了我一些问题。任何帮助或建议将不胜感激。

    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.
        }
    } 
    

2 个答案:

答案 0 :(得分:0)

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.
    }
} 

仅使用PrintTree(tree)PrintTree(tree,true)

进行调用

答案 1 :(得分:0)

另一种方法(非静态)将int封装在一个类中,并提供add和get方法。 使用此类的对象作为传递参数,在打印前添加()并在打印时获取。

在Java中,

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

int get(){
    return count;
 }
 }

现在打印时:

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