[LeetCode][Python3] 226. Invert Binary Tree
2018. 10. 3. 01:40 |
프로그래밍/LeetCode
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
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 438. Find All Anagrams in a String (0) | 2018.10.07 |
---|---|
[LeetCode][Python3] 437. Path Sum III (0) | 2018.10.07 |
[LeetCode][Python3] 283. Move Zeroes (0) | 2018.10.05 |
[LeetCode][Python3] 234. Palindrome Linked List (0) | 2018.10.04 |
[LeetCode][Python3] 206. Reverse Linked List (0) | 2018.10.01 |
[LeetCode][Python3] 198. House Robber (0) | 2018.10.01 |
[LeetCode][Python3] 169. Majority Element (0) | 2018.10.01 |
[LeetCode][Python3] 160. Intersection of Two Linked Lists (0) | 2018.09.28 |
최근에 달린 댓글 최근에 달린 댓글