Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

226. Invert Binary Tree

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

Example 1:

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

Example 2:

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

Example 3:

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

遞迴反轉

1
2
3
4
5
6
T:O(2ˆn) S:O(n)
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root: return None
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels