题目:
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
题意:翻转二叉树,交换二叉树左右孩子的位置。
代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None:
return root;
else :
self.invertTree(root.left);
self.invertTree(root.right);
root.left,root.right = root.right,root.left #交换两个变量的值
return root
笔记:
二叉树这种类型的题,一般都要用到递归来做。
这种题递归的思想很简单,只看根节点和根节点左右孩子这一层,假设左右孩子都用递归求出来了,然后看看怎么做,需要返回什么。
实在不放心,就用几个简单的例子代进去看看。
python交换两个变量的值:
a,b = b,a
多个变量的值交换:
c,b,a = a,b,c