Swift二叉树排序 递归前中后序
2020-07-07 本文已影响0人
六十亿少女的梦
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let Tree1 = TreeNode.init(1)
let Tree2 = TreeNode.init(2)
let Tree3 = TreeNode.init(3)
let Tree4 = TreeNode.init(4)
let Tree5 = TreeNode.init(5)
let Tree6 = TreeNode.init(6)
let Tree7 = TreeNode.init(7)
let Tree8 = TreeNode.init(8)
let Tree9 = TreeNode.init(9)
let Tree10 = TreeNode.init(10)
let Tree11 = TreeNode.init(11)
Tree1.left = Tree2
Tree1.right = Tree3
Tree2.left = Tree4
Tree3.left = Tree5
Tree3.right = Tree6
Tree4.right = Tree7
Tree5.left = Tree8
Tree5.right = Tree9
Tree6.right = Tree10
Tree7.left = Tree11
print(preorderTraversal(Tree1))
}
///二叉树的前序 中序 后序排序
func preorderTraversal(_ root: TreeNode?) -> [Int] {
var array = [Int]();
if root == nil {
return array;
}
//print(root?.val as Any)//前序
array.append(contentsOf: preorderTraversal(root?.left));
//print(root?.val as Any)//中序
array.append(contentsOf: preorderTraversal(root?.right));
//print(root?.val as Any)//后序
return array;
}
}