首先定义节点
typedef struct BTree
{
int value;
struct BTree *lchild;
struct BTree *rchild;
}BTree;
前序递归建立二叉树
/*
**num 前序序列
**index 下标
*/
BTree *CreateBTree(BTree *node,int *num,int& index)
{
if(num[index] == 0)
return NULL;
else
{
node = new BTree;
node -> value = num[index];
node -> lchild = CreateBTree(node->lchild,num,++index);
node -> rchild = CreateBTree(node->rchild,num,++index);
}
return node;
}
几种遍历
递归--前序遍历
void preOrder(BTree * root)
{
if(root == NULL)
return;
cout << root -> value << " ";
preOrder(root -> lchild);
preOrder(root -> rchild);
}
非递归--前序遍历
void preOrder_dxm(BTree * root)
{
stack<BTree*> S;
BTree *p = root;
while(p != NULL || !S.empty())
{
while(p != NULL)
{
cout << p -> value << " ";
S.push(p);
p = p -> lchild;
}
if(!S.empty())
{
S.pop();
if(S.empty())
return ;
p = S.top();
S.pop();
p = p -> rchild;
}
}
}
递归--中序遍历
void inOrder(BTree * root)
{
if(root == NULL)
return;
inOrder(root -> lchild);
cout << root -> value << " ";
inOrder(root -> rchild);
}
非递归--中序遍历
void inOrder_dxm(BTree * r