当前位置:网站首页>Sequential stack traversal binary tree

Sequential stack traversal binary tree

2022-06-24 20:28:00 Wukong stopped buying vegetables

Before doing this problem , You need a sequence stack , Then it's the old rule , Make the previous sequence stack into a dynamic library , It's easy to use , Students who don't know how to make sequence stacks and dynamic libraries can go to my other articles .

First go to the folder of the repository to have a look , Is there a dynamic library

It is obvious that there is such a dynamic library libseqstack.so, So it can be used directly

Let's start with a binary tree :

Analyze the traversal process :

  Let's print a tree like the one below :

Go straight to the code :

This introduces the sequence stack 1.0 Dynamic library , You can read my article

non_recursion.c

#include <stdio.h>
#include <stdlib.h>
#include "seqstack1.0.h"


// Define the data structure of each node 
typedef struct _binary_node binary_node;

struct _binary_node {
	char ch;
	binary_node *lchild;
	binary_node *rchild;
	int flag;
}; 

// Stack recursion 
void stack_print(binary_node *node)
{
	// First, initialize a stack 
	t_seq_stack* t_stack = create_stack();
	if(t_stack == NULL) {
		return;
	}
	// Directly put the root node on the stack first 
	push_stack(t_stack,node);
	// And then cycle 
	while(!is_empty(t_stack)) {
		// Take out the root node first , The left and right nodes are easy to stack 
		// Here we use preorder traversal ,DLR, that R It must be on the stack first , Finally, type it out 
		binary_node* node = (binary_node*)top_stack(t_stack);
		// And then out of the stack 
		pop_stack(t_stack);
		// Judge flag Is it equal to 1, Equal to printing 
		if(node->flag == 1) {
			printf("%c\n",node->ch);
			continue;
		}
		node->flag = 1;// The logo that pops up , Definitely from 0 become 1
		// otherwise , Turn right , Left , Connect to the root on the stack 
		if(node->rchild != NULL) {
			push_stack(t_stack,node->rchild);
		}
		if(node->lchild != NULL) {
			push_stack(t_stack,node->lchild);
		}
		// Insert the pop-up node 
		push_stack(t_stack,node);
	}
	destroy_stack(t_stack);
}

int main()
{
	// Here, create the node 
	binary_node node_a = {'A',NULL,NULL,0};
	binary_node node_b = {'B',NULL,NULL,0};
	binary_node node_c = {'C',NULL,NULL,0};
	binary_node node_d = {'D',NULL,NULL,0};
	binary_node node_e = {'E',NULL,NULL,0};
	binary_node node_f = {'F',NULL,NULL,0};

	// Connect the nodes to each other 
	node_a.lchild = &node_b;
	node_a.rchild = &node_c;

	node_b.lchild = &node_d;
	node_b.rchild = &node_e;
	
	node_c.rchild = &node_f;

	stack_print(&node_a);
	// Wear 	
	return 0;
}

  result :

 

原网站

版权声明
本文为[Wukong stopped buying vegetables]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241359148767.html