【问题标题】:How to print all nodes in Binary Search Tree only use iostream library?如何仅使用 iostream 库打印二叉搜索树中的所有节点?
【发布时间】:2020-06-25 16:51:19
【问题描述】:

我想打印树中的所有节点(低级别的节点首先打印,对于具有相同输出级别的节点,首先打印具有较小值的节点) 例如:输入

预期输出:10 6 20 1 8 18 21 7 25。 我试着这样编码

void print_Nodes(Node *root)
{
    if(root == nullptr) return;
        cout << root->value << " ";
    if(root->left!=nullptr){
        cout << root->left->value << " ";
        if(root->right!=nullptr){
            cout << root->right->value << " ";
        }
    }
    print_Nodes(root->right);
    print_Nodes(root->left);
}

但输出是:10 6 20 6 1 8 1 8 7 7 20 18 21 18 21 25。 你能指导我如何解决这个问题吗?

【问题讨论】:

  • 这个问题可以通过一点点调试变得不必要。
  • @user4581301 你能解释一下吗?
  • 评论者的意思是,您可以使用调试器单步执行代码以查看每一行的作用。虽然,您甚至不需要使用调试器,但每一行的结果很容易出现在您的屏幕上

标签: c++ tree binary-tree tree-traversal


【解决方案1】:

您正在打印root-&gt;left-&gt;value,然后调用print_Nodes(root-&gt;left),它再次打印root-&gt;value(其中root 是之前的root-&gt;left)。这就是为什么它们都会出现两次。

此外,您正在执行深度优先遍历,而您实际上想要的是广度优先遍历。要在继续下一个级别之前遍历一个级别的所有节点,您需要一个额外的数据结构来记住节点,以便您以后可以回到它们并继续向下。

#include <iostream>
#include <queue>
struct Node {
    Node* left = nullptr;
    Node* right = nullptr;
    Node(int value) : value(value) {}
    int value;
};

void bft(Node* root) {
    std::queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
        Node* current = q.front();
        q.pop();
        std::cout << current->value << " ";
        if (current->left) q.push(current->left);
        if (current->right) q.push(current->right);    
    }
}

int main() {
    Node root(10);
    Node n6(6);
    Node n20(20);
    Node n1(1);
    Node n8(8);
    Node n18(18);
    Node n21(21);
    Node n7(7);
    Node n25(25);

    root.left = &n6;
    root.right = &n20;
    n6.left = &n1;
    n6.right = &n8;
    n20.left = &n18;
    n20.right = &n21;
    n8.left = &n7;
    n21.right = &n25;

    bft(&root);
}

【讨论】:

  • 但你知道,我希望先打印低级别的节点。您的代码正在打印 Postorder 并且您的输出是 ** 10 20 21 25 18 6 8 7 1 。但我的预期输出是 **10 6 20 1 8 18 21 7 25
  • @idclev463035818:他的预期结果是广度优先,这需要一个单独的堆栈数据结构,您可以从中推送和弹出节点。他的代码和你的代码都是深度优先,使用递归调用,没有数据结构。 educative.io/edpresso/….
  • @MooingDuck 哦。感谢您的解释。我会阅读链接,也许会更新答案。最终我确实学到了一些关于写树的东西:P
猜你喜欢
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
相关资源
最近更新 更多