C
C#2y ago
Thinker

Replace node in immutable tree

I have a tree structure akin to this:
record Tree(IReadOnlyCollection<Node> Roots, IReadOnlyDictionary<string, Node> Nodes);
record Node(string Name, IReadOnlyDictionary<string, Node> Children);
record Tree(IReadOnlyCollection<Node> Roots, IReadOnlyDictionary<string, Node> Nodes);
record Node(string Name, IReadOnlyDictionary<string, Node> Children);
I wanna have a method Tree ReplaceNode(this Tree tree, Node oldNode, Node newNode) to replace nodes in this tree (i.e. return a new tree with a node replaced), but I have no idea how to do this efficiently. Is there some common algorithm or something for this?
11 Replies
Binto86
Binto862y ago
Well without having any idea about the position, just the object, you need to traverse the entire tree Can this node be anywhere, or is there bigger chance it will be in some spot in the tree?
Thinker
Thinker2y ago
Could be anywhere The main issue is that I also have to replace the node(s) in the Nodes dictionary (which contains all nodes in the entire tree) as well as in the actual nodes.
Binto86
Binto862y ago
Can you edit the dictionary? So you would also store the position in the tree? That would make it much easier and faster
Thinker
Thinker2y ago
Idk how I would store the position in the tree
Binto86
Binto862y ago
Wait a sec, let me find a diagram Nvm didnt find what i was looking for, but im pretty sure there is some standard notation for the nodes, so you can search the tree quick
Binto86
Binto862y ago
https://en.wikipedia.org/wiki/Search_tree i think this is what i thought is used
Search tree
In computer science, a search tree is a tree data structure used for locating specific keys from within a set. In order for a tree to function as a search tree, the key for each node must be greater than any keys in subtrees on the left, and less than any keys in subtrees on the right.The advantage of search trees is their efficient search time ...
Binto86
Binto862y ago
Or you could hold a pointer to the node in the tree in the dictionary, that would be probably easyer as i think about it
Thinker
Thinker2y ago
Hmm, right
Binto86
Binto862y ago
Did it work?
Jayy
Jayy2y ago
If the tree is immutable you must duplicate the tree If your just asking how to replace a node that's pretty simple Find the node, point new node to children , then point parent to newnode Done Unless it's a bst, heap etc where you have to rebalance
Thinker
Thinker2y ago
Right