-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinvert-binary-tree.py
41 lines (39 loc) · 1.07 KB
/
invert-binary-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Time: O(n)
# Space: O(h)
# DFS Stack
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is not None:
nodes = []
nodes.append(root)
while nodes:
node = nodes.pop()
node.left, node.right = node.right, node.left
if node.left is not None:
nodes.append(node.left)
if node.right is not None:
nodes.append(node.right)
return root
# Time: O(n)
# Space: O(h)
# DFS Recursive
class Solution2(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is not None:
root.left, root.right = self.invertTree(root.right), \
self.invertTree(root.left)
return root