主题:请大神看看哪里有问题 二叉树
#include<iostream>
using namespace std;
struct tree {//树结点
int data;
tree* lchild, * rchild;
int tag;//标记,初始化为0,输出后置为1表示已输出
};
tree* createtree(int* nums, int index, int n) //递归法构建二叉树
{
if (n == 0) return NULL;//判断是否为空
tree* root = new tree; //创建新结点
root->data = nums[index];
root->tag = 0;
if (index * 2 + 1 < n && nums[index * 2 + 1] != 0) //设置左右指针
root->lchild = createtree(nums, index * 2 + 1, n); //找到左孩子
else
root->lchild = NULL;
if (index * 2 + 2 < n && nums[index * 2 + 2] != 0)
root->rchild = createtree(nums, index * 2 + 2, n); //找到右孩子
else
root->rchild = NULL;
return root;
}
void lastorder1(tree* t)//递归法后序遍历: 左 右 根;
{
if (t != NULL)
{
lastorder1(t->lchild); //左
lastorder1(t->rchild); //右
if (t->lchild == NULL && t->rchild == NULL) //根
{
cout << t->data << " ";
t->tag = 1;
}
}
}
void lastorder2(tree*& t)//递归法后序遍历: 左 右 根;
{
if (t != NULL)
{
lastorder2(t->lchild); //左
lastorder2(t->rchild); //右
if (t->tag == 1) //根
t = NULL;
}
}
void lastorder(tree* t)//递归法后序遍历: 左 右 根;
{
while (t != NULL)
{
lastorder1(t);//先输出左右子节点为空的节点,并将该节点的tag置为1,表示已输出
lastorder2(t);//将节点tag为1置为空,表示已输出并清理为父节点输出作准备
}
}
int main()
{
int n;
cin >> n;
int* arr = new int[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
tree* T;
T = createtree(arr, 0, n);
lastorder(T);
return 0;
}
using namespace std;
struct tree {//树结点
int data;
tree* lchild, * rchild;
int tag;//标记,初始化为0,输出后置为1表示已输出
};
tree* createtree(int* nums, int index, int n) //递归法构建二叉树
{
if (n == 0) return NULL;//判断是否为空
tree* root = new tree; //创建新结点
root->data = nums[index];
root->tag = 0;
if (index * 2 + 1 < n && nums[index * 2 + 1] != 0) //设置左右指针
root->lchild = createtree(nums, index * 2 + 1, n); //找到左孩子
else
root->lchild = NULL;
if (index * 2 + 2 < n && nums[index * 2 + 2] != 0)
root->rchild = createtree(nums, index * 2 + 2, n); //找到右孩子
else
root->rchild = NULL;
return root;
}
void lastorder1(tree* t)//递归法后序遍历: 左 右 根;
{
if (t != NULL)
{
lastorder1(t->lchild); //左
lastorder1(t->rchild); //右
if (t->lchild == NULL && t->rchild == NULL) //根
{
cout << t->data << " ";
t->tag = 1;
}
}
}
void lastorder2(tree*& t)//递归法后序遍历: 左 右 根;
{
if (t != NULL)
{
lastorder2(t->lchild); //左
lastorder2(t->rchild); //右
if (t->tag == 1) //根
t = NULL;
}
}
void lastorder(tree* t)//递归法后序遍历: 左 右 根;
{
while (t != NULL)
{
lastorder1(t);//先输出左右子节点为空的节点,并将该节点的tag置为1,表示已输出
lastorder2(t);//将节点tag为1置为空,表示已输出并清理为父节点输出作准备
}
}
int main()
{
int n;
cin >> n;
int* arr = new int[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
tree* T;
T = createtree(arr, 0, n);
lastorder(T);
return 0;
}