编译器不了解递归功能以打印树级别的C

Compiler not understanding recursive function to print tree level-order C++

本文关键字:打印 不了解 递归 功能 编译器      更新时间:2023-10-16

我目前正在尝试解决以下问题:

用包装void void tree :: lextordorder((编写一个函数void treenode :: leveloder(int n(,以使用recursion

打印树级别订单

这是类标题:

#ifndef TREE_H
#define TREE_H
#include <algorithm>
class TreeNode {
  private:
    int key;
    TreeNode *left;
    TreeNode *right;
  public:
    TreeNode(int key);
    void insert(int key);
    void display(TreeNode *p, int lvl);
    void preOrder();
    void inOrder();
    void postOrder();
    int  size();
    int  height();
};
class Tree {
  private:
    TreeNode *root;
  public:
    Tree();
    Tree(int *a, int n);
    void insert(int key);
    void preOrder();
    void inOrder();
    void postOrder();
    void display(TreeNode *p);
    int  size();
    int  height();
};
void TreeNode::display(TreeNode *p, int lvl){
    if (p!=NULL){
        if (p->left)  display(p->left,  lvl + 4);
        if (p->right) display(p->right, lvl + 4);
    if (lvl) {
        std::cout << std::setw(lvl) << ' ';
    }
    cout << p->key << "n";
    } 
}
void Tree::display(TreeNode *p){
    if (p!=NULL){
        return display(p,0);
}

使用这两个功能,我仍会收到以下错误:

" ./tree.h:139:20:错误:呼叫的争论太多,预期单 论点" p",有2个参数 返回显示(p,3(; ~~~~~~~ ^./tree.h:137:1:注意:'显示'在此处声明void tree :: display(treenode *p({"

我不明白为什么编译器无法识别使用 2参数从Treenode类调用该函数。相反,编译器告诉我递归功能只能期待一个参数。我知道我很可能不了解这里的大图,所以有人可以尝试为我解决这个问题吗?非常感谢。

问题是在此方法中:

void Tree::display(TreeNode *p){
    if (p!=NULL){
        return display(p,0);
}

return display(p,0);表示return this->display(p,0);,并且编译器正确。

您可能的意思是p->display(p, 0);


作为旁注,两个类中的display()方法似乎都是静态方法(并且它们没有任何理由是(;他们不使用用于调用它们的对象的属性。

为了正确正确,您应该按以下方式重写它们:

void TreeNode::display(int lvl)
{
    if (left) {
        left->display(lvl + 4);
    }
    if (right) {
        right->display(lvl + 4);
    }
    if (lvl) {
        std::cout << std::setw(lvl) << ' ';
    }
    cout << key << "n";
}
void Tree::display(){
    if (root) {
        root->display(0);
    }
}