DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

5 1

Invert Binary Tree - LeetCode

Given a binary tree, you have to invert left and right nodes of it

Example:

Input

 4

/ \
2 7
/ \ / \
1 3 6 9

Output

 4

/ \
7 2
/ \ / \
9 6 3 1

Algorithm:

The intuition here is for each root node you visit swap left and right

The code would be something like

temp = root.left
root.left = root.right
root.right = temp

And we have to do this recursively for all the nodes

Code

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
  // If there is a root we swap it and if there is no root just return the value
  if(root) {
    let temp = root.left
    root.left = root.right
    root.right = temp  
    invertTree(root.left)
    invertTree(root.right)
  }
  return root
};

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay