Swift-从上往下打印二叉树

题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印.

func levelOrderTree(rootNode:TreeNode?) -> [String]? {
    if rootNode == nil {
        return nil
    }
    
    var levelArr:[String] = []
    var data:[TreeNode] = [rootNode!]
    
    while data.count > 0 {
        let headNode:TreeNode = data[0] 
        data.remove(at: 0)
        levelArr.append(headNode.data!)
        
        if headNode.leftChild != nil {
            data.append(headNode.leftChild!)
        }
        
        if headNode.rightChild != nil {
            data.append(headNode.rightChild!)
        }
    }
    
    return levelArr
}

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

var util:TreeUtil = TreeUtil()
var rootData:[String] = [“8″,”6″,”5″,”#”,”#”,”7″,”#”,”#”,”10″,”9″,”#”,”#”,”11″,”#”,”#”]
var preRootNode:TreeNode?
util.createTreeByPreOrderData(root: &preRootNode, listData: rootData)

var treeOrder:TreeOrder = TreeOrder()
var leveData:[String]? = treeOrder.levelOrderTree(rootNode: preRootNode)
print(“FlyElephant:层级数组–(leveData!)”)
print()`</code></pre>

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