[Leetcode] 226. Invert Binary Tree翻轉二叉樹
阿新 • • 發佈:2020-12-24
方法1:recursive
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root is None:
return None
left = self.invertTree(root.left)
right = self.invertTree(root.right)
root.left = right
root.right = left
return root
方法2:iterative
思路和recursive類似,遇到一個node就把當前node的left和right翻轉
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root is None:
return None
queue = [root]
while queue:
node = queue.pop()
temp = node.left
node.left = node.right
node.right = temp
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root