[LeetCode]#226. Invert Binary Tree
Jan 30, 2021
Environment: Python 3.8
Key technique: binarytree module, Recursive
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Analysis:
- Invert [2,1,3] and [7,6,9] node
- Invert [6] and [9] and [1] and [3].
- Return root
Solution:
class Solution(object):
def invertTree(self, root):if not root:
return
temp = root.left
root.left = root.right
root.right = temp
self.invertTree(root.left)
self.invertTree(root.right)
return root
Submissions:
Reference:
https://leetcode.com/problems/invert-binary-tree/discuss/1034130/Simple-Python-Recursive-Solution