DEV Community

codingpineapple
codingpineapple

Posted on

226. Invert Binary Tree

Description:

Invert a binary tree.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

// DFS approach
// In the recursion, you will traverse the tree until you hit to the bottom most leaf node
// The the right and left children of the current node will switch sides
// From the bottom going up, the ancestor nodes will switch their right and left child
// When we reach the root node, the tree will have been inverted
var invertTree = function(root) {
    // Stop when we reach a null value
    if(!root) return null;
    // Traverse the left side of the tree down to the leaf node
    const left = invertTree(root.left)
    // Traverse the right side of the tree down to the leaf node
    const right = invertTree(root.right)
    // Switch the placement of the children
    root.left = right
    root.right = left
    // Return the current node
    return root
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay