Home LeetCode - 226. Invert Binary Tree
Post
Cancel

LeetCode - 226. Invert Binary Tree

226. Invert Binary Tree - easy

문제

Invert a binary tree.

제한사항

입출력 예

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Example 1:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

풀이

  • Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func invertTree(root *TreeNode) *TreeNode {
    if root == nil {
        return root
    }
    
    invertTree(root.Left)
    invertTree(root.Right)
    
    head := root.Right
    root.Right = root.Left
    root.Left = head
    
    return root
}
This post is licensed under CC BY 4.0 by the author.