天天看點

層序(level-order)列出二叉樹的節點

資料結構與算法分析——c語言描述 練習4.35 答案

#include"fatal.h"
#include<stdlib.h>
#include<queue>
using namespace std;

typedef int ElementType;

struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;

struct TreeNode {
	ElementType element;
	SearchTree left;
	SearchTree right;
};

SearchTree GenTree(int H, int *lastNodeElem) {
	if (H >= 0) {
		SearchTree t = (SearchTree)malloc(sizeof(struct TreeNode));
		if (t == NULL)
			Error("OUT OF MEMORY");
		t->left = GenTree(H - 1, lastNodeElem);
		t->element = ++*lastNodeElem;
		t->right = GenTree(H - 1, lastNodeElem);

		return t;
	}
	return NULL;
}

SearchTree makePerfectTree(int H) {
	int lastElem = 0;
	return GenTree(H, &lastElem);
}



void dir_level(queue<pair<SearchTree,int>> nodesToTravel) {
	int level = -1;
	while(!nodesToTravel.empty()) {
		auto treeAndDepth = nodesToTravel.front();
		nodesToTravel.pop();
		if (treeAndDepth.second > level) {
			level++;
			if (level != 0)
				printf("\n");
			printf("level %d:", level);
		}
		printf("%d ", treeAndDepth.first->element);
		if (treeAndDepth.first->left)
			nodesToTravel.push({ treeAndDepth.first->left,level + 1 });
		if (treeAndDepth.first->right)
			nodesToTravel.push({ treeAndDepth.first->right,level + 1 });
	}
}

int main() {
	SearchTree t = makePerfectTree(2);
	queue<pair<SearchTree, int>> nodesToTravel;
	nodesToTravel.push({ t,0 });
	dir_level(nodesToTravel);
}