226. Invert Binary Tree

2021. 10. 26. 15:33Leetcode

Description:

Given the root of a binary tree, invert the tree, and return its root.

# 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

'''
[1] recursive - top down)

idea::
recursively invert left and right

code::
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        self.invert(root)
        return root
        
    def invert(self,root):
        if root is None:
            return
        root.left,root.right = root.right,root.left
        
        self.invert(root.left)
        self.invert(root.right)
        
-T/C: O(n) # n==the number of TreeNode
-S/C: O(h) # h==height of Tree
'''

'''
[2] iterative)

idea::
recursive solution can be converted to iterative solution using stack

code::
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        stack=[root]
        
        while stack:
            cur=stack.pop()
            
            # if cur is not None
            if cur:
                stack.append(cur.left)
                stack.append(cur.right)
                # swap
                cur.left, cur.right = cur.right, cur.left
        
        return root
        
-T/C: O(n)
-S/C: O(h)
'''
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        stack=[root]
        
        while stack:
            cur=stack.pop()
            
            # if cur is not None
            if cur:
                stack.append(cur.left)
                stack.append(cur.right)
                # swap
                cur.left, cur.right = cur.right, cur.left
        
        return root

'Leetcode' 카테고리의 다른 글

338. Counting Bits  (0) 2021.10.27
278. First Bad Version  (0) 2021.10.26
371. Sum of Two Integers  (0) 2021.10.26
33. Search in Rotated Sorted Array  (0) 2021.10.26
199. Binary Tree Right Side View  (0) 2021.10.25