Swift-二叉树的镜像

题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像.
代码:
<pre><code>`

func mirrorTree(rootNode:inout TreeNode?) -> Void {
    if rootNode == nil || (rootNode?.leftChild == nil && rootNode?.rightChild != nil) {
        return
    }
    let tempNode:TreeNode = rootNode!
    
    swap(&tempNode.leftChild, &tempNode.rightChild)
    
    if rootNode?.leftChild != nil {
        mirrorTree(rootNode: &tempNode.leftChild)
    }
    
    if rootNode?.rightChild != nil {
        mirrorTree(rootNode: &tempNode.rightChild)
    }
}`</code></pre>

测试代码:
<pre><code>`

var util:TreeUtil = TreeUtil()
var rootStr:String = “124##5##36##7##”
var preRootNode:TreeNode?
util.rootList = rootStr
util.createTreeByPreOrder(root: &preRootNode)

var treeOrder:TreeOrder = TreeOrder()

var mirrorTree:MirrorTree = MirrorTree()
mirrorTree.mirrorTree(rootNode: &preRootNode)
print(“镜像”)
treeOrder.levelOrder(preRootNode)
print()`</code></pre>

    原文作者:FlyElephant
    原文地址: https://www.jianshu.com/p/e27f1b27382a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞