본문 바로가기
알고리즘/leetcode

[Leetcode/JS] 226. Invert Binary Tree

by 질서정연_ 2023. 7. 18.

 

문제링크 

226. Invert Binary Tree

 

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.
 
 
 

Example 1:

Example 2:

Example 3:

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
 
 
 

기억하면 좋을 것 

풀기 전에는 BFS 로 node.left.left 와 node.right.right 를 바꾸고 .. 이런식으로 복잡하게 생각했었는데

단순히 생각하면 node.left과 node.right dfs로 돌리면서 해주면 되는거였다 ..... 

 

소감

 

해결 코드

var invertTree = function (root) {
    var dfs = function (node){
        if(!node) return ;
        if(!node.left && !node.right) return;

        let left = node.left;
        let right = node.right;

        node.left = right;
        node.right = left;
        
        dfs(node.left);
        dfs(node.right);
    }
    dfs(root);
    return root;
};
 
var invertTree = function(root) {
    if (root === null) return null
    let temp = root.left
    root.left = root.right
    root.right = temp 
    if(root.left) invertTree(root.left)
    if(root.right) invertTree(root.right)
    return root
};
 
 
이 풀이처럼 그냥 함수 안에서 return 해줘도 됨 
 

Submission Detail

 

댓글