728x90
recursively
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
def recu(node):
if node == None:
return
recu(node.left)
recu(node.right)
node.left, node.right = node.right, node.left
recu(root)
return root
iteratively
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
st = [root]
while len(st) > 0:
node = st.pop()
if node != None:
node.left, node.right = node.right, node.left
st.append(node.left)
st.append(node.right)
return root
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Palindrome Linked List 파이썬 (0) | 2021.04.06 |
---|---|
[LeetCode] Summary Ranges 파이썬 (0) | 2021.04.06 |
[LeetCode] Contains Duplicate II 파이썬 (dict) (0) | 2021.04.05 |
[LeetCode] Reverse Linked List 파이썬 (0) | 2021.04.05 |
[LeetCode] Isomorphic Strings 파이썬 (0) | 2021.04.05 |
댓글