提出问题:翻转一棵二叉树。(除根结点以外)
原始二叉树:
新二叉树:
解题思路:遇见二叉树先想到递归。从最下层的叶子结点开始置换左右子节点,一直置换到到最上层的根结点的左右节点为止。
代码如下( ̄▽ ̄):
# 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: if root==None: return left = invertTree(root.left) right = invertTree(root.right) root.left = right root.right = left return root
时间与空间消耗:
问题来源:https://leetcode-cn.com/problems/invert-binary-tree/submissions/
原文链接:https://www.f2er.com/python/526685.html