【问题标题】:level order traversal of binary tree using queue (array implementation)使用队列的二叉树级别顺序遍历(数组实现)
【发布时间】:2020-08-05 22:40:45
【问题描述】:

我从按级别顺序打印树节点数据的函数中得到了意外的输出。 我在不使用 STL 库的情况下跟踪级别顺序遍历的队列实现。

enter code here
#include <iostream>
using namespace std;

struct node{
int data;
node* left,*right;
};

int level_traversal(node* temp)
{
 node* arr[20];
 arr[0]=temp;
 int j=0;
 int i=0;
 while(arr[j] != NULL)
 {
  cout<<arr[j]->data<<" ";
  if(arr[j]->left != NULL)
  {
   i=i+1;
   arr[i]=arr[j]->left;
  }
  if(arr[j]->right != NULL)
  {
   i=i+1;
   arr[i]=arr[j]->right;
  }

  j=j+1;
 }

return 0;
}

node* node_creator(int value)
{
 node* temp=new node();
 temp->data=value;
 temp->left=NULL;
 temp->right=NULL;

 return temp;
}


int main() {
 node* root=node_creator(1);
 root->left=node_creator(2);
 root->right=node_creator(3);

 //left subtree
 root->left->left=node_creator(4);
 root->left->right=node_creator(5);

 level_traversal(root);
 return 0;
}

错误可能在函数的实现中,但我无法识别它

code_blocks 输出: 1 2 3 4 5 91537541

【问题讨论】:

    标签: tree binary-tree breadth-first-search


    【解决方案1】:

    在进行级别顺序遍历或 BFS 时,在队列中维护 NULL 很重要,因为编译器不会为您维护它。如果您不这样做,您将在队列末尾收到意外的输出和分段错误。

    所以代码可以通过简单的改进 第 13 行)arr[1]=NULL;

    并且在两个级别遍历函数的if语句中add) arr[i+1]=NULL;

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多