본문 바로가기
LeetCode/Problems

LeetCode 226. Invert Binary Tree

by 벤진[Benzene] 2020. 6. 20.

Problem:

Invert a binary tree.

 

Example:

-Summary-

Solved recursively

1. Until root node exist, we keep traverse left and right and change the left and right subtree by exchanging value. (By calling the function recursively)

 

Here is another solution by solving this iteratively using stack.

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

leetcode.com/problems/invert-binary-tree/discuss/62714/3-4-lines-Python

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

'LeetCode > Problems' 카테고리의 다른 글

LeetCode 628. Maximum Product of Three Numbers  (0) 2020.07.09
LeetCode 91. Decode Ways  (0) 2020.06.21
Daily Coding Problem #5  (0) 2020.06.19
Floor and Ceiling of a Binary Search Tree  (0) 2020.06.19
LeetCode 41. First Missing Positive  (0) 2020.06.18

댓글