c++ - How to fix below code for binary tree level order printing
问题描述
I have implemented below code for level order printing of nodes in a binary tree. However, it fails when a node has both left and right child.
For example, below is my binary tree.
1
\
2
\
5
/ \
3 6
\
4
Expected output is: 1 2 5 3 6 4 However, my code prints: 1 2 5 3 4 4
What is the mistake I am doing? feels like some pointer goof up.
Below are the functions I have written:
void printNodes(Node *arr[], int numOfNodes)
{
Node *outputArr[]={NULL};
int j=0;
for(int i=0; i<numOfNodes; i++)
{
printf("%d ",arr[i]->data);
if(arr[i]->left!=NULL)
{
outputArr[j++]=arr[i]->left;
}
if(arr[i]->right!=NULL)
{
outputArr[j++]=arr[i]->right;
}
}
if(j>0)
printNodes(outputArr, j);
else
return;
}
void levelOrder(Node * root) {
Node *list[]={NULL};
int ctr=0;
if(root == NULL)
return;
printf("%d ",root->data);
if(root->left != NULL)
list[ctr++]=root->left;
if(root->right != NULL)
list[ctr++]=root->right;
printNodes(list, ctr);
}
I will paste below some driver code:
main() {
Example myTree;
Node* root = NULL;
int t;
int data;
std::cin >> t;
while(t-- > 0) {
std::cin >> data;
root = myTree.insert(root, data);
}
myTree.levelOrder(root);
return 0;
}
解决方案
Assuming you are doing what you are doing for some reason, educational or otherwise, just modifying that minimally to do what I think you want your approach to do, try this:
void printNodes(std::vector<Node*> list) {
std::vector<Node*> newList;
for(int i=0; i<list.size(); i++) {
printf("%d ",list[i]->data);
if(list[i]->left) newList.push_back(list[i]->left);
if(list[i]->right) newList.push_back(list[i]->right);
}
if(!newList.empty()) printNodes(newList);
else return;
}
void levelOrder(Node * root) {
if(!root) return;
std::vector<Node*> list;
printf("%d ",root->data);
if(root->left) list.push_back(root.left);
if(root->right) list.push_back(root.right);;
printNodes(list);
}
A better solution would probably be to not use recursion at all and do the usual Breadth 1st Traversal IMO.
推荐阅读
- django - E0401: 无法导入 'django.db'
- java - 如何使用 ejp 无状态本地类在测试类中模拟私有静态 java.util.prefs.Preferences
- javascript - 将数据从父模式传递到子模式 - Vue.js
- c# - 如何根据网格视图列的路径打开文件位置?并且在我想创建“超链接”的路径中
- html - 在第二个之外添加第三个框
- excel - MATCH之后减去?匹配(查找;数组;匹配类型)-1
- jupyter-notebook - 安装 Anaconda 后运行 juypter notebook 的问题
- php - 我可以通过回调函数检测到作业状态更改为“已完成”吗
- javascript - 访问 odata 属性值 sapui5 以过滤选择列表
- javascript - 如何从javascript读取包含数组的json文件