Leetcode - 226. Invert Binary Tree

숲사람·2022년 5월 28일
0

멘타트 훈련

목록 보기
44/237

문제

트리의 left, right를 서로 바꾸는 함수를 구현하라.

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

해결

root->left 에는 right로 invert된 결과를(그의 하위 자식들도 모두 invert가 된) 저장.
root->right에는 left로 invert된 결과 저장(swap이기 때문에 temp변수이용)

struct TreeNode* invertTree(struct TreeNode* root){
    if (root == NULL)
        return NULL;
    struct TreeNode *temp = root->left;
    root->left = invertTree(root->right);
    root->right = invertTree(temp);
    return root;
}

FP스타일 by scala

230802 풀이

object Solution {
    def invertTree(root: TreeNode): TreeNode =  {
        if (root == null) null
        else new TreeNode(root.value,
            invertTree(root.right),
            invertTree(root.left))
    }
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글