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
'Python > PS in Python' 카테고리의 다른 글
LeetCode 283. Move Zeroes - Python (0) | 2020.08.16 |
---|---|
LeetCode 169. Majority Element - Python (0) | 2020.08.13 |
LeetCode 136. Single Number - Python (0) | 2020.08.06 |
LeetCode 104. Maximum Depth of Binary Tree - Python (0) | 2020.08.04 |
LeetCode 617. Merge Two Binary Trees - Python (0) | 2020.08.03 |
댓글