前、中、后序遍历都是相对于父节点说的
前序遍历
func preErgodic() -> Queue<String> {
var queue = Queue<String>()
preErgodic(node: root, queue: &queue)
return queue
}
func preErgodic(node: TreeNode?, queue: inout Queue<String>) {
if node == nil {
return
}
queue.enQueue(item: node?.key ?? "")
if node?.left != nil {
preErgodic(node: node?.left, queue: &queue)
}
if node?.right != nil {
preErgodic(node: node?.right, queue: &queue)
}
}
中序遍历
func middleErgodic() -> Queue<String> {
var queue = Queue<String>()
middleErgodic(node: root, queue: &queue)
return queue
}
func middleErgodic(node: TreeNode?, queue: inout Queue<String>) {
if node == nil {
return
}
if node?.left != nil {
// 通过递归把左子树中的所有键放入队列中
middleErgodic(node: node?.left, queue: &queue)
}
// 将节点的键放入队列中
queue.enQueue(item: node?.key ?? "")
if node?.right != nil {
// 通过递归把右子树中的所有键放入队列中
middleErgodic(node: node?.right, queue: &queue)
}
}
后序遍历
func afterErgodic() -> Queue<String> {
var queue = Queue<String>()
afterErgodic(node: root, queue: &queue)
return queue
}
func afterErgodic(node: TreeNode?, queue: inout Queue<String>) {
if node == nil {
return
}
if node?.left != nil {
afterErgodic(node: node?.left, queue: &queue)
}
if node?.right != nil {
afterErgodic(node: node?.right, queue: &queue)
}
queue.enQueue(item: node?.key ?? "")
}
网友评论