[알고리즘] LeetCode - Invert Binary Tree

Jerry·2021년 5월 26일
0

LeetCode

목록 보기
41/73
post-thumbnail

LeetCode - Invert Binary Tree

문제 설명

Given the root of a binary tree, invert the tree, and return its root.

입출력 예시

Example 1:

제약사항

The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

Solution

[전략] 재귀적으로 left child 노드와 right child 노드를 치환한다.

/**
 * Definition for a binary tree node. public 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 Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

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

        return root;
    }
}
profile
제리하이웨이

0개의 댓글