-
Notifications
You must be signed in to change notification settings - Fork 19
/
answer.py
52 lines (44 loc) · 1.39 KB
/
answer.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
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#-------------------------------------------------------------------------------
# Iterative Solution
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root: return None
stack = [root]
while stack:
curr = stack.pop()
curr.left, curr.right = curr.right, curr.left
# Add nodes to the stack
if curr.left:
stack.append(curr.left)
if curr.right:
stack.append(curr.right)
return root
#-------------------------------------------------------------------------------
# Recursive Solution
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None:
return root
root.left, root.right = root.right, root.left
if root.left:
self.invertTree(root.left)
if root.right:
self.invertTree(root.right)
return root
#-------------------------------------------------------------------------------