search
HomeJavajavaTutorialInverting a binary tree in Java

Inverting a binary tree in Java

Oct 02, 2024 am 08:07 AM

Recently, I started to practice some LeetCode exercises to improve my algorithm/data structure skills. I can say that the platform provides a good environment to practice and learn with other developers solutions in a several programming languages, discuss, share solutions with others and practice code challenges requested by big companies.

What is LeetCode?

Inverting a binary tree in Java

LeetCode is a website that helps candidates to prepare for coding interviews. Users can practice challenges by using the platform's coding and algorithmic problems, alongside with predefined tests for candidate's solution. LeetCode has become a popular resource for technical interviews and coding competitions, alongside with HackerRank.

My routine solving problems

I put myself to the goal of solving at least 3 challenges per day, and my way of thinking in a solution involves my iPad, a pen for screens and the Freeform app. I try to draw and think about the solutions, and this is helping a lot in my code submissions. A lot of challenges sounds hard at first glance, but with a few minutes thinking and architecting the solution (I recommend writing your thinking process). If I can't find the right solution in 30 minutes, then I see the submission from other developers to discover where are my mistakes (sometimes a small step that I forgot in my code). Even if your solution is good enough, I highly recommend looking at other's submissions to think in another ways of solving that problem (some more or less eficient).

The Invert Binary Tree problem

Inverting a binary tree in Java
Few days ago I faced the Invert Binary Tree problem at LeetCode, a well-known challenge requested in some interviews and a problem that I saw in when taking a Data Structures/Algorithms classes at the university. Although I never faced this challenge into an interview and haven't ever had explicitly to invert a binary tree in my work, knowing how to invert one gave me more experience with DS, Trees and algorithm thinking and practice some techniques like recursion.
I recommend you to try to solve this problem before reading the rest of this article

The solution

The Invert Binary Tree problem asked me to "Given the root of a binary tree, invert the tree, and return its root." (in other words, we should "mirror" the tree). I used Java programming language to submit a solution, but the steps are the same for other languages (with small syntax changes). The input example and expected output is shown below:

Inverting a binary tree in Java

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

We are going to use recursion technique to recursively call the invertTree() method, passing some side of the tree as a root. So, as every recursion asks, we need to define a stop condition where the recursion stack will finish and return the respective result of the recursion call. After, we just invert the sides of the tree, assigning to root.left the value returned by the recursion passing root.right as parameter, and do the same to root.right assigning the value of root.left recursion result. As we are modifying the original value, we need an auxiliary variable to store the original result of root.left (you probably implemented a code like this in university and called it swap() method.

At the end we return the root with the nodes inverted. You can check the code below:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }

        TreeNode aux = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(aux);

        return root;
    }
}

Keep in mind that could exist a lot of different solutions for different problems, and that's great. Everyone has a way of thinking and program, Data Structures domain etc. You don't need to follow this exact same code to solve this problem, but you must pay attention to the algorithm complexity (you can use 3 nested for to solve a problem, but this is less performative than using 1 for).

The above is the detailed content of Inverting a binary tree in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft