Leetcode 226. Invert Binary Tree

题目描述:倒置二叉树、左子树与右子树交换。

题目链接:Leetcode 226. Invert Binary Tree

Leetcode 226. Invert Binary Tree
题目思路:利用二叉树的层序遍历,不断交换左右子树,直到最后一层节点。

代码如下


class Solution:
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        nodes=[root]
        while(nodes):
            curr = nodes.pop(0)
            curr.left,curr.right = curr.right,curr.left
            if curr.left:
                nodes.append(curr.left)
            if curr.right:
                nodes.append(curr.right)
        return root
    

参考链接


  • Leetcode 226. Invert Binary Tree