HD201701(10.20.21.32)
二叉树的非递归遍历,我的思路
#ifndef UTILS_H_INCLUDED
#define UTILS_H_INCLUDED
#include <iostream>
using namespace std;
#define TreeNum 10 //默认十个结点,创建一个完全二叉树
typedef struct node
{
int data;
struct node *lchild;
struct node *rchild;
node(){};
node(int data)
{
this->data = data;
}
} NODE;
//创建二叉树
node *createBtree(node *root)
{
//为了方便测试,我就建立一个完全二叉树
int gap = TreeNum >> 1;
for (int i = 1; i < TreeNum; ++i)
{
(root + i)->data = i;
}
for (int i = 1; i < gap; ++i)
{
(root + i)->lchild = (root + (i << 1));
(root + i)->rchild = (root + (i << 1) + 1);
}
return (root + 1);
}
//删除二叉树
void DELETE(node *root)
{
delete root;
}
#endif
//非递归遍历
void PreTraverse(node *root)
{
node *arr[10];
int top = -1;
arr[++top] = root;
while(top>=0){
node* t = arr[top--];
printf("%d\n", t->data);
if(t->rchild){
arr[++top] = t->rchild;
}
if(t->lchild){
arr[++top] = t->lchild;
}
}
return;
}