一、二叉樹的結構
typedef struct tree
{
char date;
tree *lchil;
tree *rchil;
}tree;
二、二叉樹的創建
void create_tree(tree **root)
{
//if (root != NULL)
{
char put = ' ';
scanf("%c", &put);
if (put == '.')
*root = NULL;
else
{
*root = (tree*)malloc(sizeof(tree));
(*root)->date = put;
create_tree(&((*root)->lchil));
create_tree(&((*root)->rchil));
}
}
}
核心思想:創建一個節點,再創建它的左孩子,右孩子。一直循環這個過程,所以創建的時候使用遞歸。
三、二叉樹的先序遍歷(遞歸實現)
void pre(tree *root)
{
if (root != NULL)
{
printf("%c*",root->date);
pre(root->lchil);
pre(root->rchil);
}
}
先序遍歷:先遍歷根節點,再遍歷左孩子,再遍歷右孩子。
根據概念寫出遞歸遍歷過程。
四、二叉樹的中序遍歷(遞歸實現)
void in(tree *root)
{
if (root != NULL)
{
in(root->lchil);
printf("%c*", root->date);
in(root->rchil);
}
}
中序遍歷:先遍歷左孩子,再遍歷根節點,最後遍歷右孩子。
根據概念寫出遞歸的遍歷過程。
五、二叉樹的後序遍歷(遞歸實現)
void before(tree *root)
{
if (root != NULL)
{
before(root->lchil);
before(root->rchil);
printf("%c*", root->date);
}
}
後序遍歷:先遍歷左孩子,再遍歷右孩子,最後遍歷根節點。
根據概念寫出遍歷過程。
六、二叉樹先序遍歷(非遞歸實現)
void pre1(tree *root)
{
stack<tree*> tr;
tree *p = root;
while(p!=NULL||!tr.empty())
if (p != NULL)
{
printf("%c",p->date);
tr.push(p);
p=p->lchil;
}
else
{
p = tr.top();
tr.pop();
p = p->rchil;
}
}
七、二叉樹的中序遍歷(非遞歸實現)
中序遍歷類似於先序遍歷
void in1(tree *root)
{
stack<tree*> tr;
tree *p = root;
while (p != NULL || !tr.empty())
if (p != NULL)
{
tr.push(p);
p = p->lchil;
}
else
{
p = tr.top();
printf("%c", p->date);
tr.pop();
p = p->rchil;
}
}
八、二叉樹的後序遍歷(非遞歸實現)
void before1(tree *root)
{
stack<tree*> tr;
tree *p = root;
tree *q = root;
while (p != NULL || !tr.empty())
{
while (p != NULL)
{
tr.push(p);
p = p->lchil;
}
if(!tr.empty())
{
p = tr.top();
if (p->rchil == NULL||p->rchil==q)
{
printf("%c",p->date);
q = p;
tr.pop();
p = NULL;
}
else
p = p->rchil;
}
}
}