二叉树到指定叶子结点的路径(要求深度比树的深度小1)

/*
二叉树
求一条路径,从根结点开始到叶子结点,长度=深度-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
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值