Invert Binary Tree Leetcode Solution

Invert Binary Tree Leetcode Problem :

Given the root of a binary tree, invert the tree, and return its root.

jump game leetcode

Invert Binary Tree Leetcode Solution :

Constraints :

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Example 1:

  • Input: root = [2,1,3]
  • Output: [2,3,1]

Example 2:

  • Input: root = []
  • Output: []

Intuition :

In the question we have to Invert the binary tree.
So we use Post Order Traversal in which first we go in Left subtree and then in Right subtree then we return back to Parent node.
When we come back to the parent node we swap it’s Left subtree and Right subtree.

Approach :

  1. Traverse the given tree using level order traversal from right to left and store the node values in a vector. If any node is NULL then store any number not between [-100,100] (Node values range given in the question). So I stored -1000 for NULL nodes.

  2. Create a new node root1 and initialize it with root->val.

  3. Use Level order traversal and create a new binary tree with root node as root1

  4. if v[i]==-1000 then add NULL in the tree.

  5. Finally return root1.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription