這題的題目在這裡: 226. Invert Binary Tree
題目會給我們一顆二元樹的根節點,要求我們對齊根節點正中央的虛擬分割線,反轉整顆二元樹。
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: []
Constraints:
[0, 100]
.-100 <= Node.val <= 100
利用DFS遞迴探索整顆樹的性質,來進行鏡像反轉。
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root:
# General case:
# invert child node of current root
root.left, root.right = root.right, root.left
# invert subtree with DFS
self.invertTree( root.left )
self.invertTree( root.right )
return root
else:
# Base case:
# empty tree
return None
O( n ) 每個節點最多拜訪一次。
O( n ) 空間成本耗費在遞迴呼叫時所建立的call stack,
最深的那一層在最後一層,當樹向左歪斜或向右歪斜時,
最深的深度可以到O( n )
[1] Python/JS/Java/Go/C++ O(n) by DFS [w/ Visualization] — Invert Binary Tree — LeetCode