二叉树
定义
typedef struct node*
link;
struct node
... {
Item item;
link l, r;
};
struct node
... {
Item item;
link l, r;
};
二叉树的先序遍历(递归)
void traverse(link h, void (*
visit)(link))
... {
if(h == NULL) return;
(*visit)(h);
traverse(h->l, visit);
traverse(h->r, visit);
}
... {
if(h == NULL) return;
(*visit)(h);
traverse(h->l, visit);
traverse(h->r, visit);
}
二叉树的先序遍历(非递归)
void traverse(link h, void (*
visit)(link))
... {
STACKinit(max);
STACKpush(h);
while(!STACKempty())
...{
(*visit)(h = STACKpop());
if(h->r != NULL) STACKpush(h->r); //右子树入栈
if(h->l != NULL) STACKpush(h->l); //左子树入栈
}
}
... {
STACKinit(max);
STACKpush(h);
while(!STACKempty())
...{
(*visit)(h = STACKpop());
if(h->r != NULL) STACKpush(h->r); //右子树入栈
if(h->l != NULL) STACKpush(h->l); //左子树入栈
}
}
若将上面的栈改为队列,则此遍历变为层序遍历
void traverse(link h, void(*
visit)(link))
... {
QUEUEinit(max);
QUEUEput(h);
while(!QUEUEempty())
...{
(*visit)(h = QUEUEget());
if(h->l != NULL) QUEUEput(h->l);
if(h->r != NULL) QUEUEput(h->r);
}
}
... {
QUEUEinit(max);
QUEUEput(h);
while(!QUEUEempty())
...{
(*visit)(h = QUEUEget());
if(h->l != NULL) QUEUEput(h->l);
if(h->r != NULL) QUEUEput(h->r);
}
}
树参数的计算
计算树的节点数(递归)
int
count(link h)
... {
if(h == NULL) return 0;
return count(h->l)+count(h->r)+1;
}
... {
if(h == NULL) return 0;
return count(h->l)+count(h->r)+1;
}
计算树的高度(递归)
int
height(link h)
... {
int u, v;
if(h == NULL) return -1;
u = height(h->l);
v = height(h->r);
if(u > v) return u+1;
else return v+1;
}
... {
int u, v;
if(h == NULL) return -1;
u = height(h->l);
v = height(h->r);
if(u > v) return u+1;
else return v+1;
}