1.问题描述:
翻转一棵二叉树。
2.样例:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
3.代码:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val self.left,
self.right = None, None
"""
class Solution:
"""
@param: root: a TreeNode, the root of the binary tree
@return: nothing
"""
def invertBinaryTree(self, root):
# write your code here
if root is None:
return None
node=root.left
root.left=root.right
root.right=node
self.invertBinaryTree(root.left)
self.invertBinaryTree(root.right)
这三步是在对父结点的两个左右子树进行交换,借助中间变量node。
node=root.left
root.left=root.right
root.right=node
之后再递归调用函数。
注意:一般树的题都会对根做一个特殊空的判断。