路径:树中两个结点之间的 路径 是由这两个结点之间所经过的结点序列构成的。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MaxSize 50
//打印结点x的所有祖先
//打印从根结点到某个结点的路径
void printPres(BiTree T,int x){
BiTree stack[MaxSize],p = T;
int top = -1,tag[MaxSize] = {0};
while(p || top != -1){
if(p){
stack[++top] = p;
p = p->lchild;
tag[top] = 1;
}else{
p = stack[top];
if(tag[top] == 1){
p = p->rchild;
tag[top] = 2;
}else{
top--;
if(p->data == x){
for(int i = 0,i<=top,i++)
printf("%d",stack[i]->data);
}
p = NULL;
}
}
}
}
路径长度:路径上所经过的边的个数
所以,如果 栈的top的初始值为-1,所求结点的 路径长度 就等于此时top的值,故返回的是 top.
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MaxSize 50
//求从根结点到某个结点的路径长度
int xPathLength(BiTree T,int x){
BiTree stack[MaxSize],p = T;
int top = -1,tag[MaxSize] = {0};
while(p || top!=-1){
if(p){
stack[++top] = p;
p = p->lchild;
tag[top] = 1;
}else{
p = stack[top];
if(tag[top] == 1){
p = p->rchild;
tag[top] = 2;
}else{
if(p->data == x){
return top;
}
top--;
p = NULL;
}
}
}
return -1;
}
//从根结点到某个结点最大路径长度
int getMaxPath(BiTree T){
BiTree stack[MaxSize],p = T;
int top = -1,tag[MaxSize] = {0},max = 0;
while(p || top != -1){
if(p){
stack[++top] = p;
p = p->lchild;
tag[top] = 1;
}else{
p = stack[top];
if(tag[top]==1){
p = p->rchild;
tag[top] = 2;
}else{
if(!p->lchild && !p->rchild){
if(top > max)
max = top;
}
top--;
p = NULL;
}
}
}
return max;
}