
문제링크
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

'알고리즘 > leetcode' 카테고리의 다른 글
| [LeetCode/MSSQL] 1327. List the Products Ordered in a Period (1) | 2024.01.28 | 
|---|---|
| [LeetCode/MSSQL] 196. Delete Duplicate Emails (1) | 2024.01.28 | 
| [Leetcode/JS] 404. Sum of Left Leaves (0) | 2023.07.17 | 
| [Leetcode/JS] 111. Minimum Depth of Binary Tree (0) | 2023.07.13 | 
| [leetcode/JS] 234. Palindrome Linked List / Javascript (0) | 2022.08.27 | 
										
									
										
									
										
									
										
									
댓글