问题描述
Invert a binary tree.
颠倒一个二叉树
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
Python 实现
# 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 None
else:
tNode = root.left
root.left = self.invertTree(root.right)
root.right = self.invertTree(tNode)
return root

本文介绍了一种颠倒二叉树的算法实现,通过递归方式交换二叉树节点的左右子节点,实现了二叉树结构的反转。提供了一个Python代码示例,展示了颠倒二叉树的具体操作。
1463

被折叠的 条评论
为什么被折叠?



