이 문제는 트리를 좌우구조를 뒤집어주는 문제입니다.
전체 트리 구조를 뒤집기위해 각각의 노드를 어떻게 해야할지 살펴보면 결국 각 노드의 왼쪽 자식과 오른쪽 자식 노드를 바꿔주면 됩니다.
모든 노드의 자식 노드들을 바꿔줘야 하므로 DFS를 사용했습니다.
Recursion
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) // node가 비어있으면
return nullptr;
// 왼쪽 자식 노드와 오른쪽 자식 노드를 바꿔줍니다. (Swap)
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
// 자식 노드가 있다면 이동
if (root->left)
invertTree(root->left);
if (root->right)
invertTree(root->right);
return root;
}
};
재귀가 아닌 stack을 사용할 수 있습니다.
TreeNode* invertTree(TreeNode* root) {
// stack
if (!root)
return nullptr;
std::stack<TreeNode*> s;
s.push(root);
while(!s.empty()) {
TreeNode* cur = s.top();
s.pop();
// 두 자식 노드 swap
TreeNode* temp = cur->left;
cur->left = cur->right;
cur->right = temp;
// 이동
if (cur->left)
s.push(cur->left);
if (cur->right)
s.push(cur->right);
}
return root;
}
'Algorithm 문제풀이 > Leetcode' 카테고리의 다른 글
(Easy - DP) Leetcode - 303. Range Sum Query - Immutable (0) | 2024.06.26 |
---|---|
(Easy - DP) Leetcode - 70. Climbing Stairs (0) | 2024.06.26 |
(Easy - DFS) Leetcode - 572. Subtree of Another Tree (0) | 2024.06.25 |
(Easy - DFS) Leetcode - 104. Maximum Depth of Binary Tree (0) | 2024.06.24 |
(Easy - DFS) Leetcode - 543. Diameter of Binary Tree (0) | 2024.06.24 |