今晚感觉不错,56个题,错了6个,一看是关于二叉树链表的有2个,所以需要重视这部分。
二叉链表存储结构,交换分支点左右子树算法:
f(Node* root,Node* child)
{
if (root==child) {output the stack;return;}
if (root->left) {
stack.push(root->left);
f(root->left,child);
stack.pop();
}
if (root->right) {
stack.push(root->right);
f(root->right,child);
stack.pop();
}
}
void main()
{
stack.push(root);
f(root,child);
}
程序没检测,就是这个大概意思,路径要用堆栈来保存!!
-----------------------------------------------------------------------------
(1)编写建立二叉树的算法。
(2)验证二叉树的先序、中序、后序遍历算法
(3)编写二叉树的左右子树交换算法
上面这些都比较简单,程序如下:
#include <stdio.h>
#include <malloc.h>
typedef struct tree
{
char data;
struct tree *l;/*左儿子*/
struct tree *r;/*右儿子*/
}tr;
/*先序建立二叉树*/
tr *create(tr *t)
{
tr *k=NULL;
char ch;
scanf("%s",&ch);
if(ch=='#')
{
t=NULL;
}
else
{
t=(tr *)malloc(sizeof(tr));
t->data=ch;
t->l=create(k);
t->r=create(k);
}
return t;
}
/*先序遍历*/
void preOrder(tr *t)
{
if(t)
{
printf("%c/t",t->data);
preOrder(t->l);
preOrder(t->r);
}
}
/*中序遍历*/
void inOrder(tr *t)
{
if(t)
{
inOrder(t->l);
printf("%c/t",t->data);
inOrder(t->r);
}
}
/*后序遍历*/
void postOrder(tr *t)
{
if(t)
{
postOrder(t->l);
postOrder(t->r);
printf("%c/t",t->data);
}
}
/*左右子树交换*/
void switchChild(tr *t)
{
if(t)
{
tr *temp;
temp=t->l;
t->l=t->r;
t->r=temp;
switchChild(t->l);
switchChild(t->r);
}
}
main()
{
tr *head=NULL;
head=create(head);
printf("/n The preOrder is:");
preOrder(head);
printf("/n The inOrder is:");
inOrder(head);
printf("/n The postOrder is:");
postOrder(head);
printf("/n");
switchChild(head);
}
------------------------------------------------------------------------
关于二叉链表概念:http://www.doc88.com/p-08368579078.html
---------------------------------------------------------------------------