其他分享
首页 > 其他分享> > leetcode学习笔记(翻转二叉树-递归/迭代)

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

作者:互联网

226. 翻转二叉树

在这里插入图片描述

递归
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

标签:node,right,invertTree,迭代,queue,二叉树,root,leetcode,left
来源: https://blog.csdn.net/qq_43656500/article/details/120794921