Contents

[Golang][Leetcode][BinaryTree]刷題系列-226-Invert Binary Tree


226. Invert Binary Tree


Level : Easy

原題連結 : Click

題目 :

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


Example :

Note

Example 1:

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

Example 2:

Input: root = [2,1,3] Output: [2,3,1]

Example 3:

Input: root = [] Output: []


解題思路 :

  • 這題屬於binary tree的基本題,直接照著邏輯作即可!

我的解法

  • time complexity: O(n) , space complexity: O(1)

Runtime: 0 ms, faster than 100.00% of Go online submissions for Invert Binary Tree.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * 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
    }
    
    var Invert func(node *TreeNode)
    
    Invert = func(node *TreeNode) {
        
        if node.Left != nil {
            Invert(node.Left)
        }
        
        if node.Right != nil {
            Invert(node.Right)   
        }
        node.Left, node.Right = node.Right, node.Left

    }
    
    Invert(root)
    
    return root
}

最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!