Skip to content

Commit d78c9f8

Browse files
committed
invert binary tree
1 parent 1a88fda commit d78c9f8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

226.InvertBinaryTree.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
226. Invert Binary Tree
3+
Easy
4+
Tree | Depth-First Search | Breadth-First Search | Binary Tree
5+
---
6+
Given the root of a binary tree, invert the tree, and return its root.
7+
8+
Example 1:
9+
Input: root = [4,2,7,1,3,6,9]
10+
Output: [4,7,2,9,6,3,1]
11+
12+
Example 2:
13+
Input: root = [2,1,3]
14+
Output: [2,3,1]
15+
16+
Example 3:
17+
Input: root = []
18+
Output: []
19+
20+
Constraints:
21+
The number of nodes in the tree is in the range [0, 100].
22+
-100 <= Node.val <= 100
23+
"""
24+
25+
from typing import Optional
26+
27+
28+
# Definition for a binary tree node.
29+
class TreeNode:
30+
def __init__(self, val=0, left=None, right=None):
31+
self.val = val
32+
self.left = left
33+
self.right = right
34+
35+
36+
class Solution:
37+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
38+
if root:
39+
root.left, root.right = self.invertTree(root.right), self.invertTree(
40+
root.left
41+
)
42+
return root

0 commit comments

Comments
 (0)