Published:
Updated:


Solution

package leetcode.sully.week4;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}


class L226 {
    public TreeNode invertTree(TreeNode root) {
//        javax.swing.tree.TreeNode
        // λ°”μ΄λ„ˆλ¦¬ 트리: λ…Έλ“œλ§ˆλ‹€ μžμ‹μ΄ 2 μ΄ν•˜μΈ 트리
        // κ·Έλ‹ˆκΉŒ λ°°μ—΄μ—μ„œ 1-2-2-2-2-2... 이런 μ‹μœΌλ‘œ κ΅¬λΆ„ν•˜λ©΄ 됨

        // νŠΈλ¦¬μ—μ„œλŠ” μ—„λ§ˆ λ…Έλ“œλ³΄λ‹€ μž‘μ€ 데이터가 μ™Όμͺ½ μžμ‹ λ…Έλ“œμ— 와야 ν•˜κ³ 
        // μ—„λ§ˆ λ…Έλ“œλ³΄λ‹€ 큰 데이터가 였λ₯Έμͺ½ μžμ‹ λ…Έλ“œμ— 와야 함

        // root = [4,2,7,1,3,6,9]
        // <4> / (2), [7] / {1}, {3} -> (2) / {6}, {9} -> [7]

        // val: int ν˜•
        // left, right : TreeNode ν˜•

//        if (root.right == null) {
//            root.right = new TreeNode(root.val);
//        }
//
//        if (root.left == null) {
//            root.left = new TreeNode(root.val);
//        }

//        TreeNode val = new TreeNode(root.val);
//        TreeNode left = new TreeNode(root.left.val);
//        TreeNode right = new TreeNode(root.right.val);
//
//        TreeNode treeNode = new TreeNode(val.val, left.right, right.left);

        if (root == null) {
            return null;
        }

        TreeNode right = invertTree(root.right);
        TreeNode left = invertTree(root.left);

        root.left = right;
        root.right = left;

        return root;
    }
}

Leave a comment