1.문제
Given the root of a binary tree, invert the tree, and return its root.
이진 트리가 주어질 때 왼쪽 서브트리와 오른쪽 서브트리가 뒤집어진 트리를 리턴하는 문제이다.
Example 1

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

Input: root = [2,1,3]
Output: [2,3,1]
Example 3
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
2.풀이
- 재귀함수를 이용해서 현재 root의 왼쪽 자식과 오른쪽 자식 노드를 바꿔준다.
/**
* 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}
*/
const invertTree = function (root) {
if (root === null) {
return root;
} else {
let temp = root.left;
root.left = root.right;
root.right = temp; // 왼쪽 자식과 오름쪽 자식 노드 교환
invertTree(root.left); // 왼쪽 서브트리로 진행
invertTree(root.right); // 오른쪽 서브트리로 진행
return root;
}
};
3.결과
