乐趣区

Leetcode226-翻转二叉树-Python实现

  • 题目要求:

  • 思路:

    • 递归
    • 走到底,如果以后节点存在,那么把以后节点的左节点右节点调换
    • 返回上一层
  • 代码:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        self.helper(root)
        return root
    
    def helper(self, node):
        if node:
            self.helper(node.left)
            self.helper(node.right)

            node.left, node.right = node.right, node.left
退出移动版