Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

reverse binary tree c

// For embeded systems, dont use recursion, use stack (or queue) instead
// For more details check https://iq.opengenus.org/invert-binary-tree/

/*
typedef struct stack {
	stack_node_t* top;
} stack_t;

typedef struct stack_node {
	tree_node_t* t_node;	// Value of the stack node
    stack_node_t* next;
}stack_node_t;
*/

// What else you will likely need
stack_t* init_stack();
void stack_push();
tree_node_t* stack_pop();


void reverse_tree(tree_node_t* root) {
	
	if (root != NULL) {

      stack_t* stack = init_stack();	// Initialize stack
      tree_node_t* node, temp;	// Binary tree nodes


      while (stack->top != NULL) {
        
        // Dont forget to free the stack node inside the stack_pop()
		node = stack_pop(stack);

        temp = node->left_child;
        node->left_child = node->right_child;
        node->right_child = temp;

        if ( node->left_child != NULL ) stack_push (stack, node->left_child);

        if ( node->right_child != NULL ) stack_push (stack, node->rigth_child);


      }
		
      free(stack);
      
	}


}
 
PREVIOUS NEXT
Tagged: #reverse #binary #tree
ADD COMMENT
Topic
Name
4+5 =