二叉树常见的四种遍历方式,先序遍历,中序遍历,后序遍历以及层次遍历,先来看一张二叉树的图:
遍历之前我们可以先自己实现树,不过为了效率,可以通过函数自己创建树~
二叉树创建
方式一:
var d = TreeNode(data: "d",leftChild: nil,rightChild: nil)
var b = TreeNode(data: "b",leftChild: nil,rightChild: d)
var e = TreeNode(data: "e",leftChild: nil,rightChild: nil)
var c = TreeNode(data: "c", leftChild: nil, rightChild: e)
var a = TreeNode(data: "a",leftChild: b,rightChild: c)
print("FlyElephant")
print("先序遍历:")
preOrder(a)
print("\n中序遍历:")
inOrder(a)
print("\n后序遍历:")
postOrder(a)
print()
方式二,输入一个先序的二叉树序列,空节点设置为#,以上图为例:
let rootList="ABD##E##CF###"
var rootIndex = -1
func createTree(inout root:TreeNode?) -> Void {
rootIndex=rootIndex+1
if rootIndex>=rootList.characters.count {
return
}
let data=rootList[rootIndex] as String
if data != "#" {
root = TreeNode()
root?.data = data
createTree(&root!.leftChild)
createTree(&root!.rightChild)
} else {
root = nil
}
}
二叉树的定义:
class TreeNode: NSObject {
var data:NSString?
var leftChild:TreeNode?
var rightChild:TreeNode?
override init() {}
init(data:NSString,leftChild:TreeNode?,rightChild:TreeNode?) {
self.data = data
self.leftChild = leftChild
self.rightChild = rightChild
}
}
先序遍历
遍历的顺序:根节点->左节点->右节点
func preOrder(rootNode:TreeNode?) -> Void {
if rootNode != nil {
if let data = rootNode?.data {
print("\(data)\t", terminator: "")
preOrder(rootNode?.leftChild)
preOrder(rootNode?.rightChild)
}
}
}
中序遍历
遍历的顺序:左节点->根节点->右节点
func inOrder(rootNode:TreeNode?) -> Void {
if rootNode != nil {
if let data = rootNode?.data {
inOrder(rootNode?.leftChild)
print("\(data)\t", terminator: "")
inOrder(rootNode?.rightChild)
}
}
}
后序遍历
遍历的顺序:左节点->右节点->根节点
func postOrder(rootNode:TreeNode?) -> Void {
if rootNode != nil {
if let data = rootNode?.data {
postOrder(rootNode?.leftChild)
postOrder(rootNode?.rightChild)
print("\(data)\t", terminator: "")
}
}
}
层次遍历
遍历的方式从上到下,从左到右:
func levelOrder(rootNode:TreeNode?) -> Void {
var arr:[AnyObject]=[];
arr.append(rootNode!);
while arr.count>0 {
let firstNode=arr[0] as! TreeNode
if let data=firstNode.data {
print("\(data)\t", terminator: "")
arr.removeFirst()
}
if (firstNode.leftChild != nil) {
arr.append(firstNode.leftChild!)
}
if (firstNode.rightChild != nil) {
arr.append(firstNode.rightChild!)
}
}
}
测试
let rootList="ABD##E##CF###"
var rootIndex = -1
func createTree(inout root:TreeNode?) -> Void {
rootIndex=rootIndex+1
if rootIndex>=rootList.characters.count {
return
}
let data=rootList[rootIndex] as String
if data != "#" {
root = TreeNode()
root?.data = data
createTree(&root!.leftChild)
createTree(&root!.rightChild)
} else {
root = nil
}
}
var rootNode:TreeNode?
createTree(&rootNode)
print("先序遍历:")
preOrder(rootNode)
print("\n中序遍历:")
inOrder(rootNode)
print("\n后序遍历:")
postOrder(rootNode)
print("\n层次遍历:")
levelOrder(rootNode)
测试结果如图所示: