should a tree have exactly one root node - c#

I want to display a tree structure. Do i really need to give the user/tree a predefined hardcoded root node like "RootUnit" where he can add his children or descendants?
Does this make sense or cause only trouble when adding nodes?

If you have two roots then you have two trees.

A tree should have only one root. But you need not hardcode a root. Just treat the first created tree node as root.

A tree by definition has only one root and every child node has exactly one parent (except the root which has no parent). If these restrictions are not met then your tree is no longer a tree but a graph (oriented or not)

It depends on the context. From a strict mathematical definition, you cannot have multiple root nodes to a tree. However, there some implementations of trees that ignore that and have multiple top level nodes anyway (Such as the TreeView control you tagged this question with). You simply need to ask yourself if your particular program would be better or worse with multiple top level nodes. Given that we know nothing else about your program it's not a decision we can really make for you.

Rather than using the same constructor for every node, supply a default constructor used for the root node and one for everything else. It isn't ugly, and it works.
public Node()
{
// Set properties if you'd like.
// such as having no children yet or whatnot.
}
public Node(Node parent)
{
// Similar to Node()
}
See! Nice and clean.

Related

Traversing/comparing tree structures with only parent references

Consider a tree structure with nodes containing references to only their parent. So, the root node's parent will be null. This tree represents a class hierarchy. The goal is to search such a tree for a particular subtree, and if it doesn't exist, add it to the tree. Is there an algorithm that can be used to achieve this?
In this particular case, I have a C# WinForms application which uses this kind of structure. At the moment, an iterative breadth-first traversal is being used to traverse through such a tree and display it as a treeView. How this is being done is as follows: To represent the nodes of the tree itself, there is a class Data_Node. To perform the traversal, the nodes are placed into a queue. The queue contains instances of a data structure, QueueNode:
private class QueueNode
{
public Model.Data_node dataNode; // actual tree node
public QueueNode parent; // reference to the parent
public TreeNode treeNode; // node for treeView in the UI
}
The next step is to implement another such tree (assume it is already, then check whether it is a subtree of the first one, and add it if it is not.
I have researched examples of what I am trying to achieve, but they were only for binary search trees, with nodes having references to the child nodes. In my case, the nodes only have references to the parent node.

Syntax rewriting

I need to transform all of the properties of a certain class using Roslyn.
What is the recommended way to apply more than one transformation to a syntax tree without invalidating references into it?
Here is what I've tried and where I'm stuck:
In the first pass a descendant of CSharpSyntaxWalker is visiting all PropertyDeclarationSyntax nodes, and storing them in a list.
In the second pass a CSharpSyntaxRewriter is transforming the nodes while checking that each visited node equals one in the list before transforming it.
The problem with my attempt is: When I transform a property I add new fields to the class which causes the class to mutate. All the references in the list to the other properties become invalid in the new tree for the class.
It seems to be inefficient to revisit the whole class, and either way I cannot detect the property nodes already handled due to the reference difference.
I would not recommend to reference nodes from a SyntaxTree you want to modify. In your case just using a CSharpSyntaxRewriter in a single pass (without keeping references from a pre-processing pass) would be sufficient, because its VisitPropertyDeclaration method will only be called once per property, so there is no need to keep track of the nodes you've already modified.
The CSharpSyntaxRewriter also visits the nodes bottom-up, so the overrides should always be called with a node from the original tree. Most likely you have modified the node through the call to base.VisitPropertyDeclaration() before comparing its reference to the stored one. So you could still keep and compare references if you really wanted to.
public class PropertyRewriter : CSharpSyntaxRewriter
{
public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node)
{
// 'node' should be still from the original syntax tree here
node = (PropertyDeclarationSyntax)base.VisitPropertyDeclaration(node);
// 'node' might be replaced here
return node;
}
}
Instead of keeping references to the nodes you want to modify, you could annotate them. Annotations to a node will survive modifications of the containing SyntraxTree as long as the node itself isn't replaced. You can add them like this:
node = node.WithAdditionalAnnotations(
new SyntaxAnnotation("propertyToChange", "todo"));
To retrieve the annotation again either use node.GetAnnotations("propertyToChange") or use GetAnnotatedNodesOrTokens("propertyToChange") to retrieve all nodes or tokens with an annotation of the given kind ("propertyToChange").

Recursive tuple

I am trying to create a recursive Tuple in C#. One side is a reference a class, and the other side goes into recursion to a likewise datastructure. The right side can be null, and this is when the recursion ends.
At the moment I am using an alias, but this does not seem to work.
using Relation = System.Tuple<Node, Relation>;
Directly typing this is not possible, as this goes infinite.
System.Tuple<Node, System.Tuple<Node, System.Tuple<Node, ...>>>
1.
Is this possible in C#?
2.
Can I do this with aliases?
Extra info
I am doing this because I need to keep track the parent of each node. A node can have multiple children. I cannot edit the node class.
I only need to go up the hierarchy. i.e. I don't need to know a nodes children. I use this for an algorithm where I calculate alot of nodes, and when I find one, I want to find the path to it from bottom to root.
You can create a Class for this.
class Relation
{
Node Node; // Node is another class
Tuple<Node, Relation> Relation;
}

Children or Parent based Tree Structure

I'm developing a class that will be used to generate a tree structure. Each Node of the tree needs to know both who it's parent is and who it's children are. The fields used to track each Nodes parent and children are not accessible outside the base Node class.
Right now I have methods for AddChild, and Remove child. Which consequently also set the parent fields of the instances being related.
So what I'm wondering now is if it would be any better or worse to switch this and setup methods where the user of the class has to call Node.SetParent(Node parentNode) and Node.ClearParent(Node oldParentNode) methods instead.
If you are tracking both parent and child relationships, why would you choose to set the child relationships over the parents or vise versa, or does it even matter?
In either case, when you are attaching a node to the tree you will need a reference to both the parent and the child node in question, so I don't see how it would make a difference, as either way will be equally possible in all situations.
I'd suggest figuring out which direction your logic will make the most sense (i.e. is it easier to think about building the tree from the leaves up or the root down) and go with that.
Decisions like these typically depend on how the class will be used. If a typical scenerio is for a tree to be build from the parent node down, then using an AddChild method is often best, if your users build them from the other way around, give the a SetParent method. If there is a need for both, implement both, so long as the appropriate book keeping is done internal to the class.
(side note: I usually build trees from the parent down)
I think you need all three methods. When building a tree, the AddChild method would seem more natural. There are two reasons to remove a node. One is to get rid of it, and the other is to reorganise the tree (move a subtree to another branch). When deleting, RemoveChild works well. But reorganisation could use the SetParent method to avoid making two calls. SetParent could also become a transaction of sorts.

Can I find Logical Children by Type

I know i can use LogicalTreeHelper class to find children node for every element searching it by name. But is there a possibility to find a child node by Type? For example, what if i would like to find a ListBox element in my Window without knowing its Name property??
I don't think that there is a built in way of doing this. Probably the best approach would be to recursively call LogicalTreeHelper.GetChildren() until a child control of the specified type is found.
Note that descending the Logical tree cleanly is actually a little tricky, here's a nice article on the intricacies of both the visual and logical trees.
I don't think any helper code exists to do this for you so implementing a recursive walk over the tree is required.

Categories

Resources