【iOS】【数据结构】二叉树的遍历

二叉树的遍历方式有三种
1、前序遍历NLR(Preorder Traversal,先序遍历
2、中序遍历LNR(Inorder Traversal)
3、后序遍历LRN(Postorder Traversal)

代码
Swift

class TreeNode {
    var val: Int
    var left: TreeNode?
    var right: TreeNode?
    init(_ val: Int) {
        self.val = val
        self.left = nil
        self.right = nil
    }
}

1、前序

func treeTraversal(_ t: TreeNode?) -> Void {
    if let tree = t {
        print("\(tree.val)")
        seeTrees(tree.left)
        seeTrees(tree.right)
    }
}

2、中序

func treeTraversal(_ t: TreeNode?) -> Void {
    if let tree = t {
        seeTrees(tree.left)
        print("\(tree.val)")
        seeTrees(tree.right)
    }
}

3、后序

func treeTraversal(_ t: TreeNode?) -> Void {
    if let tree = t {
        seeTrees(tree.left)
        seeTrees(tree.right)
        print("\(tree.val)")
    }
}

你可能感兴趣的:(【iOS】【数据结构】二叉树的遍历)