찾다
Javajava지도 시간Java에서 이진 트리 반전

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).

위 내용은 Java에서 이진 트리 반전의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경