Invert Binary Tree Solutions in Python
Number 226
Difficulty Easy
Acceptance 65.1%
Link LeetCode
Solutions
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/invert-binary-tree/# Author : penpenps# Time : 2019-08-01# Recursive# Time Complexity: O(n), the number of tree's nodes# Space Complexity: O(h), the height of tree# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution:def invertTree(self, root: TreeNode) -> TreeNode:if not root: return rootif root.left:root.left = self.invertTree(root.left)if root.right:root.right = self.invertTree(root.right)if root.left or root.right:root.left, root.right = root.right, root.leftreturn root
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/invert-binary-tree/# Author : penpenps# Time : 2019-08-01# BFS, iterative# Time Complexity: O(n), the number of tree's nodes# Space Complexity: O(n), the max node number by level# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution:def invertTree(self, root: TreeNode) -> TreeNode:if not root: return rootqueue = [root]while queue:node = queue.pop(0)node.left, node.right = node.right, node.leftif node.left:queue.append(node.left)if node.right:queue.append(node.right)return root