题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印.
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>