Java에서 이진 트리 반전
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?
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
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:
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











일부 애플리케이션이 제대로 작동하지 않는 회사의 보안 소프트웨어에 대한 문제 해결 및 솔루션. 많은 회사들이 내부 네트워크 보안을 보장하기 위해 보안 소프트웨어를 배포 할 것입니다. ...

시스템 도킹의 필드 매핑 처리 시스템 도킹을 수행 할 때 어려운 문제가 발생합니다. 시스템의 인터페이스 필드를 효과적으로 매핑하는 방법 ...

데이터베이스 작업에 MyBatis-Plus 또는 기타 ORM 프레임 워크를 사용하는 경우 엔티티 클래스의 속성 이름을 기반으로 쿼리 조건을 구성해야합니다. 매번 수동으로 ...

많은 응용 프로그램 시나리오에서 정렬을 구현하기 위해 이름으로 이름을 변환하는 솔루션, 사용자는 그룹으로, 특히 하나로 분류해야 할 수도 있습니다.

IntellijideAultimate 버전을 사용하여 봄을 시작하십시오 ...

Java 객체 및 배열의 변환 : 캐스트 유형 변환의 위험과 올바른 방법에 대한 심층적 인 논의 많은 Java 초보자가 객체를 배열로 변환 할 것입니다 ...

전자 상거래 플랫폼에서 SKU 및 SPU 테이블의 디자인에 대한 자세한 설명이 기사는 전자 상거래 플랫폼에서 SKU 및 SPU의 데이터베이스 설계 문제, 특히 사용자 정의 판매를 처리하는 방법에 대해 논의 할 것입니다 ...

데이터베이스 쿼리에 tkmyBatis를 사용하는 경우 쿼리 조건을 구축하기 위해 엔티티 클래스 변수 이름을 우아하게 가져 오는 방법이 일반적인 문제입니다. 이 기사는 고정 될 것입니다 ...
