二叉树输出根结点到每个叶结点的路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HarvestWu/article/details/83097011
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#define MaxSize 100
#define ArrayLen(array) sizeof(array)/sizeof(array[0])
/*
* Created by HarvestWu on 2018/10/16.
*/
using namespace std;


//定义二叉树结构
typedef struct BTNode{
	int key;
	struct BTNode *lchild;
	struct BTNode *rchild;
} BTNode,*BiTree;

typedef struct Queue{
	struct BTNode *data[MaxSize];
	int rear = 1;
	int front = 1;
};

//二叉排序树关键字插入
int BSTInsert(BiTree &bt, int key){
	if (bt == NULL){
		bt = (BTNode*)malloc(sizeof(BTNode));
		bt->lchild = bt->rchild = NULL;
		bt->key = key;
		return 1;
	}
	else{
		if (key == bt->key)
			return 0;
		else if (key < bt->key)
			return BSTInsert(bt->lchild, key);
		else return BSTInsert(bt->rchild, key);
	}
}

//创建二叉排序树
void CreateBST(BiTree &bt, int key[], int n){
	bt = NULL;
	for (int i = 0; i < n; ++i)
		BSTInsert(bt, key[i]);
}

//输出根结点到每个结点路径
void RootToLeaf(BiTree bt, Queue q){
	if (bt!=NULL){
		q.data[q.rear++] = bt;
		if (bt->lchild == NULL&&bt->rchild == NULL){
			while (q.front<q.rear)
				cout << q.data[q.front++]->key << " ";
			cout << endl;
		}
		RootToLeaf(bt->lchild,q);
		RootToLeaf(bt->rchild,q);
		
	}
}

//二叉排序树中序遍历
void inOrder(BiTree bt){
	if (bt != NULL){
		inOrder(bt->lchild);
		cout << bt->key << " ";
		inOrder(bt->rchild);
	}
}

int main(){
	BiTree bt;
	int key[] = { 5, 3, 6, 2, 4, 1 };
	int n = ArrayLen(key);
	CreateBST(bt, key, n);
	//inOrder(bt);
	Queue q;
	RootToLeaf(bt,q);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/HarvestWu/article/details/83097011