题目:根据二叉树的先序遍历结果构建二叉树.

创建二叉树
<pre><code>` func createTreeByPreOrder(root:inout TreeNode?,listData:[String]) {
rootIndex = rootIndex + 1
if rootIndex >= listData.count {
return
}
let data:String = listData[rootIndex] as String
if data == "#" {
root = nil
} else {
root = TreeNode()
root?.data = data
createTreeByPreOrder(root: &root!.leftChild, listData: listData)
createTreeByPreOrder(root: &root!.rightChild, listData: listData)
}
}`</code></pre>
层次遍历二叉树
<pre><code>` func treeLevelOrder(root:TreeNode?) {
if root == nil {
return
}
var arr:[TreeNode] = []
arr.append(root!)
while arr.count > 0 {
let firstNode:TreeNode = arr[0]
if firstNode.data != nil {
print("\(firstNode.data!)\t", terminator: "")
arr.removeFirst()
}
if firstNode.leftChild != nil {
arr.append(firstNode.leftChild!)
}
if firstNode.rightChild != nil {
arr.append(firstNode.rightChild!)
}
}
print("")
}`</code></pre>
测试代码:
<pre><code>`var tree:Tree = Tree()
var preListData:[String] = ["1","2","4","#","#","5","7","#","#","#","3","#","6","#","#"]
var preOrderRoot:TreeNode?
tree.createTreeByPreOrder(root: &preOrderRoot, listData: preListData)
tree.treeLevelOrder(root: preOrderRoot)
print("FlyElephant")`</code></pre>

网友评论