본문 바로가기
Problem Solving

[Leetcode] 226. Invert Binary Tree

by leeyngdo 2023. 7. 13.

Problem Link: https://leetcode.com/problems/invert-binary-tree/

 

Invert Binary Tree - LeetCode

Can you solve this real interview question? Invert Binary Tree - Given the root of a binary tree, invert the tree, and return its root.   Example 1: [https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg] Input: root = [4,2,7,1,3,6,9] Output: [4

leetcode.com

 

Solution 1. Recursion (DFS)

Time: $O(N)$

Space: $O(1)$ 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        # None
        if root is None:
            return None
        else:
            # Invert
            root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
            return root

Solution 2. Stack (DFS)

Time: $O(N)$

from collections import deque

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root: return None

        q = deque(); q.append(root)
        while q:
            node = q.pop()
            node.left, node.right = node.right, node.left
            
            if node.left: q.append(node.left)
            if node.right: q.append(node.right)
            
        return root

Solution 3. Queue (BFS)

Time: $O(N)$

from collections import deque

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root: return None
        
        q = deque(); q.append(root)
        while q:
            node = q.popleft()
            node.left, node.right = node.right, node.left

            if node.left: q.append(node.left)
            if node.right: q.append(node.right)
            
        return root

 

'Problem Solving' 카테고리의 다른 글

[Leetcode] 704. Binary Search  (0) 2023.07.17
[Leetcode] 242. Valid Anagram  (0) 2023.07.13
[Leetcode] 125. Valid Palindrome  (0) 2023.07.12
[Leetcode] 121. Best Time to Buy and Sell Stock  (0) 2023.07.12
[Leetcode] 20. Valid Parentheses  (0) 2023.07.11