/*
二叉树
求一条路径,从根结点开始到叶子结点,长度=深度-1
多条输出最左边的一条
思路:
1、求二叉树的深度
2、层序遍历 1数值和长度是否符合 2是不是叶子结点
参照
二叉树从根结点到指定结点的路径问题
后序非递归遍历的变体
注意:由于栈是从-1开始计数的,所以栈非空的条件必须设置为top>=0,而不能设置为top>0,否则就会出现错误
输入:深度为3的满二叉树124##5##36##7##
分别输入结点4 5 2 3查看路径
*/
#include <iostream>
#include <malloc.h>
using namespace std;
const int maxsize = 100;
typedef struct BiTNode{
char data;
struct BiTNode *lchild, *rchild;
}*BiTree;
void creTree(BiTree &T){
char c;
cin >> c;
if(c=='#')
T = NULL;
else{
T = (BiTree)malloc(sizeof(BiTNode));
T->data = c;
creTree(T->lchild);
creTree(T->rchild);
}
}
int getDepth(BiTree T){
int lchildDepth, rchildDepth;
if(!T) return 0; //空树的高度为0
else{
lchildDepth = getDepth(T->lchild);
rchildDepth = getDepth(T->rchild);
return (lchildDepth>rchildDepth) ? (lchildDepth+1) : (rchildDepth+1);
}
}
void getPath(BiTree T, char c){
BiTree p, stack[maxsize];
int depth = getDepth(T);
int top = -1;
int tag[maxsize]; //0表示该结点未被扫描过
p = T;
do{
//靠左的结点全部入栈
while(p){
stack[++top] = p; //结点入栈
tag[top] = 0;
p = p->lchild;
}
//栈非空
if(top>=0){
//结点已经访问过
if(tag[top] == 1){
if(stack[top]->data==c && top==depth-2){ //保证数值符合,深度符合
if(stack[top]->lchild==NULL && stack[top]->rchild==NULL){ //保证是叶子结点
printf("路径为:");
for(int i=0; i<=top; i++)
printf("%c ", stack[i]->data);
printf("\n");
break; //结点不重复就退出,结点有重复就继续
}
}
top--;
}
//结点未访问过
else{
p = stack[top];
p = p->rchild; //扫描右结点
tag[top] = 1; //该结点已被扫描过
}
}
}while(top>=0 || p); //栈非空 或者 p结点不为空--继续循环
}
int main(){
BiTree T;
char c;
cout << "输入二叉树结点:";
creTree(T);
cout << "输入尾结点:";
cin >> c;
getPath(T, c);
return 0;
}
二叉树到指定叶子结点的路径(要求深度比树的深度小1)
最新推荐文章于 2022-09-03 18:02:03 发布