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???
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With