题目: 反转二叉树其实就是二叉树的镜像.
4
/
2 7
/ \ /
1 3 6 9
to
4
/
7 2
/ \ /
9 6 3 1
核心代码:
<pre><code>` func invertTree(rootNode:TreeNode?) {
if rootNode == nil || (rootNode?.leftChild == nil && rootNode?.rightChild == nil) {
return
}
let root:TreeNode = rootNode!
swap(&root.leftChild, &root.rightChild)
if root.leftChild != nil {
invertTree(rootNode: root.leftChild)
}
if root.rightChild != nil {
invertTree(rootNode: root.rightChild)
}
}`</code></pre>
测试代码:
<pre><code>`var invertNode:TreeNode?
var invertListData:[String] = ["4","2","1","#","#","3","#","#","7","6","#","#","9","#","#"]
tree.rootIndex = -1
tree.createTreeByPreOrder(root: &invertNode, listData: invertListData)
tree.treeLevelOrder(root: invertNode)
binaryTree.invertTree(rootNode: invertNode)
tree.treeLevelOrder(root: invertNode)
print("FlyElephant")`</code></pre>