Leetcode/Top 100 Liked

[Binary Tree][Easy] 226. Invert Binary Tree

자전거통학 2024. 3. 14. 21:48

https://leetcode.com/problems/invert-binary-tree/description

 

Q. 주어진 tree를 좌우전환 하여라. 

 

Solution. 

 단순히 node의 자식들을 반대로 연결한다. 

 

    TreeNode* invertTreeBT(TreeNode* node)
    {
        if(node == NULL)    return NULL;

        TreeNode* leftTemp = node->left;
        node->left = invertTreeBT(node->right);
        node->right = invertTreeBT(leftTemp);
        return node;
    }

public:
    TreeNode* invertTree(TreeNode* root)
    {
        return invertTreeBT(root);
    }

 

 

결과.