DEV Community

kster
kster

Posted on

Invert Binary Tree

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

Diagram showing a binary tree next to a binary tree that has been inverted

  • First we will have to look at the root node, take its children, swap the positions of the children, then recursively run invert on both right and left subtrees. DFS will allow us to solve this problem

Depth For Search (DFS) - is an algorithm for traversing or searching tree. The algorithm starts at the root node and explores as far as possible along each branch before backtracking.

class Solution:
   def invertTree(self, root: TreeNode) -> TreeNode:
      if not root:
         return None
      # swap the positions of the children
      #saving the left value in a temporary variable
      tmp = root.left 
      #replacing the left value(root.left) to with right value(root.right)
      root.left =root.right 
      #replacing the right value(root.right) with the left which we saved as "tmp"
      root.right = tmp 

      #invert left subtree
      self.invertTree(root.left) 
      #invert right subtree
      self.invertTree(root.right) 
      return root
Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay