目录
1、创建一个TreeNode的Class
public class TreeNode {
var val: Int
var left: TreeNode?
var right: TreeNode?
init() {
self.val = 0; self.left = nil; self.right = nil
}
init(_ val:Int) {
self.val = val; self.left = nil; self.right = nil
}
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
// 这里复写了 == 比较方法,用于非递归后序遍历使用。主要是通过内存地址来判断是否为同一个节点
static func == (a: TreeNode, b: TreeNode) -> Bool {
return a.getAnyObjectMemoryAddress(object: a) == b.getAnyObjectMemoryAddress(object: b)
}
// 取出某个对象的地址
func getAnyObjectMemoryAddress(object: AnyObject) -> String {
let str = Unmanaged<AnyObject>.passUnretained(object).toOpaque()
return String(describing: str)
}
}
2、递归实现前、中、后序的遍历
代码量比较少,也比较简单
// 前序
func fristRootTree(_ root: TreeNode?) {
if root == nil { return }
print("\(root!.val) -> ")
fristRootTree(root!.left)
fristRootTree(root!.right)
}
// 中序
func middleRootTree(_ root: TreeNode?) {
if root == nil { return }
middleRootTree(root!.left)
print("\(root!.val) -> ")
middleRootTree(root!.right)
}
// 后序
func lastRootTree(_ root: TreeNode?) {
if root == nil { return }
lastRootTree(root?.left)
lastRootTree(root?.right)
print("\(root!.val) -> ")
}
3、非递归实现
前序遍历
思路