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

题目链接: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

相关文章:

  • 2021-08-21
  • 2022-12-23
  • 2021-07-25
  • 2022-12-23
  • 2021-09-01
  • 2021-08-31
猜你喜欢
  • 2021-06-16
  • 2022-02-14
  • 2021-12-20
  • 2021-08-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案