VOOZH about

URL: https://www.geeksforgeeks.org/dsa/flip-binary-tree/

⇱ Flip Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Flip Binary Tree

Last Updated : 23 Oct, 2024

Given a binary tree, the task is to flip the binary tree towards the right direction that is clockwise.

Input:

👁 flip-binary-tree-1

Output:

👁 flip-binary-tree-2


Explanation: In the flip operation, the leftmost node becomes the root of the flipped tree and its parent becomes its right child and the right sibling becomes its left child and the same should be done for all leftmost nodes recursively. 

[Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space

The idea is to recursively flip the binary tree by swapping the left and right subtrees of each node. After flipping, the tree's structure will be reversed, and the new root of the flipped tree will be the original leftmost leaf node.

Below is the main rotation code of a subtree: 

  • root->left->left = root->right
  • root->left->right = root
  • root->left = NULL
  • root->right = NULL
👁 flip-binary-tree-3

Below is the implementation of the above approach: 


Output
2 
3 1 
4 5 

[Expected Approach - 2] Iterative Approach - O(n) Time and O(n) Space

The iterative solution follows the same approach as the recursive one, the only thing we need to pay attention to is saving the node information that will be overwritten

Below is the implementation of the above approach: 


Output
2 
3 1 
4 5 
Comment
Article Tags:
Article Tags: