c++ - 如何显示当前级别的节点?

标签 c++ binary-tree

根据实数输入序列构建二叉搜索树。显示
具有用户指定级别的节点中的值。
我无法弄清楚寻找值和算法的原理。
如何为这种算法编写函数


#include <iostream>

using namespace std;

struct Node
{

  int data;
  Node *left;
  Node *right;
};
Node *root = NULL;

void InsertNode(int x, Node *leaf)
{
  Node *new_node = new Node;
  new_node->data = x;
  new_node->left = NULL;
  new_node->right = NULL;
  if (leaf == NULL)
    root = new_node;
  else

      if (x < leaf->data)

    if (leaf->left != NULL)

      InsertNode(x, leaf->left);

    else

      leaf->left = new_node;

  else

      if (x >= leaf->data)

    if (leaf->right != NULL)

      InsertNode(x, leaf->right);

    else

      leaf->right = new_node;
}



int main()
{

  int x, n = 0;
  cout << "Enter 10 numbers" << endl;
  for (int i = 0; i < 10; i++)
  {

    cin >> x;
    InsertNode(x, root);
  }


  system("pause");
  return 0;
}

如何根据我的结构显示当前级别的节点
struct Node
{

  int data;
  Node *left;
  Node *right;
};
Node *root = NULL;

最佳答案

这样的事情怎么样

void print_level(Node *root, int level)
{
  if (! level)
    cout << root->data;
  else
  {
    print_level(root->left, level - 1);
    print_level(root->right, level - 1);
  }
}

然后调用该函数
print_level(root, 3);

它将打印深度为3的所有节点。(假设根节点位于级别0。)

关于c++ - 如何显示当前级别的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61063091/

相关文章:

java - 用 map 实现树

C++11:使用容器参数定义函数(如基于范围的 for)?

c++ - Xcode 8.2 无法从添加的搜索路径中找到头文件?

c++ - 使用编译时递归生成从 1 到 499 的素数

自应用程序启动以来获取时间的 c++ 可移植方法?

c++ - 非递归删除二叉树的问题

C++ 贷款合格金额

c - 使用 fork() 的二叉进程树

java - 二叉排序树中的 compareTo 方法

c - 突破C中的递归函数