简体   繁体   中英

Swift playground execution aborted

I'm trying to write an algorithm to search a tree but am getting this error: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). on the last line of code where I call the function to execute, not sure what's going on here, does someone know what the problem is?

class Node {
    let value: Int
    var leftChild: Node?
    var rightChild: Node?

    init(value: Int, leftChild: Node?, rightChild: Node?) {
        self.value = value
        self.leftChild = leftChild
        self.rightChild = rightChild
    }
}

let oneNode = Node(value: 1, leftChild: nil, rightChild:  nil)
let fiveNode = Node(value: 5, leftChild: oneNode, rightChild: nil)
let twentyNode = Node(value: 20, leftChild: nil, rightChild: nil)
let elevenNode = Node(value: 11, leftChild: nil, rightChild: nil)
let fourteenNode = Node(value: 14, leftChild: elevenNode, rightChild: twentyNode)
let tenRootNode = Node(value: 10, leftChild: fiveNode, rightChild: fourteenNode)

func inOrderTraversal(node: Node?){
    if(node != nil){
        inOrderTraversal(node: node?.leftChild!)
        print(node?.value)
        inOrderTraversal(node: node?.rightChild!)
    }
}

inOrderTraversal(node: tenRootNode)

You're force-unwrapping optional values here:

inOrderTraversal(node: node?.leftChild!)
print(node?.value)
inOrderTraversal(node: node?.rightChild!)

but many of your nodes have nil values for their left and right children, so it crashes. Just don't force-unwrap them, as your inOrderTraversal method takes an optional Node anyway:

inOrderTraversal(node: node?.leftChild)
print(node?.value)
inOrderTraversal(node: node?.rightChild)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM