Python/PS in Python
LeetCode 226. Invert Binary Tree - Python
Air’s Big Data
2020. 8. 9. 11:51
LeetCode 226. Invert Binary Tree - Python
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Solution :
class Solution(object):
def invertTree(self, root):
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack += node.left, node.right
return root
(솔루션 출처)
https://gist.github.com/ryuji0123/
더보기
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# def traverse(self, root):
# if not root: return
# root.left, root.right = root.right, root.left
# self.invertTree(root.left)
# self.invertTree(root.right)
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
# My answer
# self.traverse(root)
# return root
# Another answer
# if root:
# root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
# return root
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack += node.left, node.right
return root
(참고 사이트)
이진트리 학습 구조 : https://chohyeonkeun.github.io/2019/07/04/190704-datastructure-binarytree/
이진트리 반전시키기 : https://www.youtube.com/watch?v=rkt34Yt4KIo
self, __init__ 관련 질문 답변 : https://www.inflearn.com/questions/4642
__init__() 메서드와 self 인자 : https://dojang.io/mod/page/view.php?id=2373