Algorithm

LeetCode 226 - Invert Binary Tree

쿠케캬캬 2023. 2. 18. 13:19
반응형

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

 

트리를 후위 순회하면서, 방문했던 좌측 노드와 우측 노드를 스왑해주었습니다.

전위 순회하여도 동일한 결과를 얻을 수 있습니다.

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root) return NULL;
        invertTree(root->left);
        invertTree(root->right);
        swap(root->left, root->right);
        return root;
    }
private:
    void swap(TreeNode*& a, TreeNode*& b) {
        TreeNode* temp = a;
        a = b;
        b = temp;
    }
};
반응형