PS/LeetCode

LeetCode / Tree / 226번 / Invert Binary Tree / JS

KimMinJun 2023. 4. 28. 17:28

< 문제 바로가기 >

 

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

 

< 문제 간단설명 >

주어진 트리를 좌우반전시켜 반환하는 문제이다.

 

/**
 * 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);

    [root.left, root.right] = [root.right, root.left];

    return root;
};