Problem :

https://leetcode.com/problems/invert-binary-tree/description/


My Solution :

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root:
root.left, root.right = (
self.invertTree(root.right), self.invertTree(root.left))
return root


Comment :

위 방법은 Recursion을 활용한 것이다. 80칸 넘어가는걸 괄호 열고 개행했는데 뭐가 최선의 컨벤션인지 잘 모르겠다.

아래는 Iterative이다. Stack을 쓰든 Queue를 쓰든 아무런 상관이 없다.


My Solution2 :

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack.extend([node.left, node.right])
return root