7-2 Si se debe completar el árbol de búsqueda binaria (la secuencia del árbol atraviesa la cola)

Si encuentra un nodo que no es de segundo grado, entonces si el árbol es un árbol completo, todas las hojas detrás del nodo deben serlo.

Hay circunstancias especiales: cuando el árbol tiene solo dos nodos, la raíz debe tener un grado menor que 2 y el otro nodo deben ser hojas, pero este árbol no es un árbol completo.

Entonces, cuando el número de nodos es mayor que 2, se puede usar el método general y cuando solo hay dos nodos, es mejor generar directamente como un caso especial.

En cuanto al recorrido de secuencia, se pueden utilizar colas. Cuando visite un nodo, coloque a su hijo izquierdo al final del equipo y luego coloque al hijo derecho al final del equipo. Los nodos de la capa superior deben estar delante de la capa inferior en la cola y están ordenados de izquierda a derecha.

El código incluye el establecimiento del árbol, el uso de colas y la salida de la secuencia. En la función de salida de secuencia de capas, se utilizan dos variables bool para juzgar la completitud por cierto.

//输入大小
//输入数字
//	生成树
//	进行层序遍历
//	如果某一个结点的没有两个子树
		//那么接下去的结点都不能有两个子树

#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#include<stdbool.h>

static int n;
//标记树的完全性
static bool sign1 = false;
static bool sign2 = false;



struct TNode{
    
    
	int  value;
	struct TNode* Left;
	struct TNode* Right;
};


struct TNode* insert(struct TNode* root, int data) {
    
    
	//新建叶子
	if (root == NULL) {
    
    
		root = (malloc)(sizeof(struct  TNode));
		root->value = data;
		root->Left = NULL;
		root->Right = NULL;
		return root;
	}
	else {
    
    
		if (data > root->value) {
    
    
			root->Left = insert(root->Left, data);
		}
		else {
    
    
			root->Right = insert(root->Right, data);
		}
	}
	return root;
}


//队列及操作
struct Queue {
    
    
	struct TNode* array[30];
	int front;
	int top;
	int count;
}q;

void initialQueue() {
    
    
	q.front = q.top = 0;
	q.count = 0;
}

void push(struct TNode* data) {
    
    
	q.array[q.top] = data;
	q.top++;
	q.count++;
}

struct TNode* pop() {
    
    
	struct TNode* data = q.array[q.front];
	q.front++;
	q.count--;
	return data;
}

struct TNode* front() {
    
    
	return q.array[q.front];
}

bool isEmpty() {
    
    
	return q.count == 0;
}



//队列方式实现层序输出
void levelOut(struct TNode* root) {
    
    
	//加入根结点
	push(root);
	while (!isEmpty()) {
    
    
		struct TNode* tempFront = pop();



		if (tempFront->Left != NULL) {
    
    
			push(tempFront->Left);
		}
		if (tempFront->Right != NULL) {
    
    
			push(tempFront->Right);
		}

		//输出控制.........
		if (!isEmpty())
			printf("%d ", tempFront->value);
		else
			printf("%d", tempFront->value);
		//... ......

		//判断完全性
		//有一个不为二度的结点 则后面的都要是叶子
		if (sign1== false&&(!(tempFront->Left != NULL && tempFront->Right != NULL))) {
    
    
			sign1 = true;
			continue;
		}
		if (sign1 == true) {
    
    
			if (!(tempFront->Left == NULL && tempFront->Right == NULL)) {
    
    
				sign2 = true;
			}
		}
		//特别讨论只有两个结点的情况
		if (n == 2) {
    
    
			sign2 = true;
		}
	
	}
		

	printf("\n");
	}




//在层序输出时做好标记
int main() {
    
    
	struct TNode* treeRoot = NULL;
	scanf("%d", &n);
	//导入结点
	for (int i = 0; i < n; i++) {
    
    
		int toInsert;
		scanf("%d", &toInsert);
		treeRoot= insert(treeRoot, toInsert);
	}
	levelOut(treeRoot);

	if (!sign2) {
    
    
		printf("YES");
	}
	else {
    
    
		printf("NO");
	}

	return 0;
}

Supongo que te gusta

Origin blog.csdn.net/roswellnotfound/article/details/108995500
Recomendado
Clasificación