###### tags: `Tree & Binary Tree`
# Leetcode 226. Invert Binary Tree
1. 問題描述
Given the root of a binary tree, invert the tree, and return its root.
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: []
2. Input的限制
* The number of nodes in the tree is in the range [0, 100].
* -100 <= Node.val <= 100
3. 思考流程
* Recursive
基本上我採由上至下的寫法。如果 parent 為空就 return,不然就進行左右子樹交換,然後讓左右子樹的 root 當 parent,逐層遞迴往下交換,直到 leaves 為止。<br>
因為需要走遍整棵 binary tree,故 time complexity 是 O(N)。最差的情況就是,整棵 binary tree 的 nodes 都在 stack 中,而 space complexity 是 O(N)。
Time Complexity: O(N); Space Complexity: O(N)
* Iterative
迭代的方法有點類似 BFS。首先創造一個 queue,然後把 root 丟入 queue 中,如果 queue 不空的話,拿出 queue 最前面的元素,對它的左右子樹進行交換,然後把左右子樹各自的 roots 丟進 queue 內。這樣整個 queue 做完後,所有的 nodes 其子樹都交換一遍。<br>
因為需要走遍整棵 binary tree,故 time complexity 是 O(N)。最差的情況就是,整棵 full binary tree 的 leaves 都在 queue 中,而 nodes 總數為 2^k^-1,leaves 的數量為 2^k-1^,推得 leaves 的數量為 (n+1)/2,所以 space complexity 是 O(N)。
Time Complexity: O(N); Space Complexity: O(N)
4. 測試
* test 1
root = [2,1,3,4,5]
Output: [2,3,1,5,4]