728x90
반응형
226. Invert Binary Tree
LeetCode
https://leetcode.com/problems/invert-binary-tree/description/
Invert Binary Tree - LeetCode
Can you solve this real interview question? Invert Binary Tree - Given the root of a binary tree, invert the tree, and return its root. Example 1: [https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg] Input: root = [4,2,7,1,3,6,9] Output: [4
leetcode.com
Given the root of a binary tree, invert the tree, and return its root.
이진 트리의 루트(root)가 주어졌을 때, 트리를 좌우 반전(invert)한 후 그 루트를 반환하시오.
Example

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

Input: root = [2,1,3]
Output: [2,3,1]
Input: root = []
Output: []
1. 문제 요구사항 분석
이진트리 좌우 반전하기
2. 접근 전략
😁 임시 TreeNode를 이용한 swp 진행. left, right 트리를 서로 바꾸기
/**
* 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 root;
// 임시 TreeNode 이용한 swp
TreeNode tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);
return root;
}
}728x90
반응형
'프로그래밍 > 알고리즘' 카테고리의 다른 글
| [LeetCode] 125. Valid Palindrome (0) | 2026.06.17 |
|---|---|
| [LeetCode] 200. Number of Islands (0) | 2026.06.15 |
| [LeetCode] 242. Valid Anagram (0) | 2026.06.09 |
| [LeetCode] 190. Reverse Bits (0) | 2026.06.03 |
| [LeetCode] 56. Merge Intervals (0) | 2026.06.01 |