简体   繁体   中英

Swift: Binary Tree Search with int not in tree

I am going through Ray Weynderlich's Swift Algo Club files and he uses this code for getting the tree height:

   func findTreeHeight() -> Int {

        if isLeaf {
            return 0
        } else {
            return 1 + max(leftChild?.findTreeHeight() ?? 0, rightChild?.findTreeHeight() ?? 0)
        }

    }

If I create the tree with this array:

let myTree = BinaryTree(arrValues: [7, 2, 5, 10, 9, 1])

Shouldn't the height be 4? I am getting 2.

Here's the inits and insertion functions:

init(value:Int) {
        self.value = value
    }

    convenience init(arrValues:Array<Int>) {

        precondition(arrValues.count > 0)
        self.init(value: arrValues.first!)
        for thisValue in arrValues.dropFirst() {
            insertValue(value: thisValue)
        }
    }

    func insertValue(value:Int) {

        if value < self.value {
            //insert on left
            if let leftChild = self.leftChild {
                leftChild.insertValue(value: value)
            } else {
                leftChild = BinaryTree(value: value)
                leftChild?.parent = self
            }
        } else {
            //insert on right
            if let rightChild = self.rightChild {
                rightChild.insertValue(value: value)
            } else {
                rightChild = BinaryTree(value: value)
                rightChild?.parent = self
            }
        }
    }

and an extension to pseudo print it out

extension BinaryTree: CustomStringConvertible {
    public var description: String {
        var s = ""
        if let left = leftChild {
            s += "(\(left.description)) <- "
        }
        s += "\(value)"
        if let right = rightChild {
            s += " -> (\(right.description))"
        }
        return s
    }
}

Here's the link where I was following along:

https://github.com/raywenderlich/swift-algorithm-club/tree/master/Binary%20Search%20Tree

The height is 2 that is correct. It's the number of edges in the longest path from the node to a leaf node.

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