본문 바로가기

리트코드/easy

[리트코드] 226. Invert Binary Tree - js

반응형

1. 문제

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

2. 코드

/**
 * 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}
 */
var invertTree = function(root) {
    if(root === null) return root;
    // 자식 노드부터 순서 바꾸고 올라오는 재귀 형태
    invertTree(root.left);
    invertTree(root.right);

    const cur = root.left;
    root.left = root.right;
    root.right = cur;

    return root;
};

파라미터 설명을 잘 보자!

반응형