leetcode学习笔记(翻转二叉树-递归/迭代)

226. 翻转二叉树

leetcode学习笔记(翻转二叉树-递归/迭代)

递归
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return root
        
        left = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left, root.right = right, left
        return root
迭代
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return root

        queue = [root]
        while queue:
            node = queue.pop()
            node.left, node.right = node.right, node.left            
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return root
上一篇:翻转二叉树


下一篇:翻转二叉树