swift后序创建二叉树

如后序遍历得到如下字符串:##H##ID##EB###JF##GCA
对应二叉树如图一所示:


图一.jpeg
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        var arr = Array(String("ABDH##I##E##CF#J##G##")) //先序
//        var arr = Array(String("#H#D#I#B#E#A#F#J#C#G#A"))
        //后期
        let arr = Array(String("##H##ID##EB###JF##GCA"))
        test.index = arr.count - 1
        let list = NodeList()
        list.root = list.createPostBT(arr)
        
        print(list.preOder(list.root))
    }
}

struct test {
    static var index : Int = 0
}
class Node{
    var val : Character
    var left : Node?
    var right : Node?
    init(_ val : Character) {
        self.val = val
        self.left = nil
        self.right = nil
    }
}
class NodeList {
    var root : Node?
    func createPostBT(_ arr : [Character]) -> Node?{
        let val = arr[test.index]
        test.index -= 1
        var node : Node? = nil
        if val != "#"{
            node = Node(val)
            node?.right = createPostBT(arr)
            node?.left = createPostBT(arr)
        }
        return node
    }
    func preOder(_ node : Node?) -> [Character]{
        var res = [Character]()
        preOrderHelper(node, arr: &res)
        return res
    }
    func preOrderHelper(_ node : Node?,arr : inout [Character]) {
        if let node = node{
            arr.append(node.val)
            preOrderHelper(node.left,arr :&arr)
            preOrderHelper(node.right,arr :&arr)
        }
    }
    
}

打印结果:

["A", "B", "D", "H", "I", "E", "C", "F", "J", "G"]

你可能感兴趣的:(swift后序创建二叉树)