Answers for "reverse binary tree c"

C
0

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);
      
	}


}
Posted by: Guest on April-17-2022
0

reverse binary tree c

void reverse_tree(tree_node_t* root) {
	
    if (root != NULL) {
    	
        // Reverse left and right sub-tree
        reverse_tree(root->left_child);
        reverse_tree(root->right_child);
        
        // Reverse two child nodes
        tree_node_t *temp = root->right_child;
        root->right_child = root->left_child;
        root->left_child  = temp;
        
	}

}
Posted by: Guest on April-16-2022

Code answers related to "C"

Browse Popular Code Answers by Language