Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Tree with struct in swift

I was trying to make a binary tree with the help of struct as given below:

struct BinaryTree {
    var value: Int
    var left: BinaryTree
    var right: BinaryTree 
}

But I am getting error error: value type 'BinaryTree' cannot have a stored property that recursively contains it. Here struct is value type so I can't create same struct object in it.

How can I achieve this???

like image 664
Chanchal Chauhan Avatar asked Oct 15 '25 03:10

Chanchal Chauhan


2 Answers

Structs are value types that's the reason why recursion won't work. You have to use Class instead, because they are reference types. But as you said you want a solution with value types. Here is a solution for you using enum

Enums with indirect cases are allocated on the heap and thus contain only pointers to the recursive children. Without pointer indirection, the type would otherwise be infinitely large, since it contains infinitely many times.

enum BinaryTree<Element: Comparable> {
    case empty
    indirect case node(value: Element, left: BinaryTree<Element>, right: BinaryTree<Element>)
}

extension BinaryTree {
    func addNode(_ newValue: Element) -> BinaryTree<Element> {
        switch self {
        case .empty:
            return BinaryTree.node(value: newValue, left: .empty, right: .empty)
        case let .node(value, left, right):
            if newValue < value {
                return BinaryTree.node(value: value, left: left.addNode(newValue), right: right)
            } else {
                return BinaryTree.node(value: value, left: left, right: right.addNode(newValue))
            }
        }    
    } 
}

let tree = BinaryTree<Int>.empty.addNode(2)

OR

You simply just use Class

You can use class for this structure, structs do not allow to reference itself.

class BinaryTree {
    var value: Int
    var left: BinaryTree?
    var right: BinaryTree?
    init(value: Int) {
        self.value = value
    }
}

I hope this will work for you.

like image 114
BilalReffas Avatar answered Oct 17 '25 11:10

BilalReffas


You can use class for this structure, structs do not allow to reference itself.

class BinaryTree {
    var value: Int?
    var left: BinaryTree?
    var right: BinaryTree?
    init(value: Int) {
        self.value = value
    }
}

let node = BinaryTree.init(value: 1)
node.left = BinaryTree(value: 2)

The reason for this compile error is memory allocation: Value types are fixed structures and they occupy a fixed space in memory, in registers and the stack, depending on its size. That space is pre-determined by the type and must be known at compile time.

https://medium.com/@leandromperez/bidirectional-associations-using-value-types-in-swift-548840734047

like image 28
ymutlu Avatar answered Oct 17 '25 12:10

ymutlu