How to get the second father if my position was the leaf .
for example :
1---->2---->3
or
1---->2---->3---->4
or
1---->2---->3---->4---->5
if i'm in the last node (3 or 4 or 5)
How to get the text of node (2)?
foreach (RadTreeNode node in nodeCollection)
{
if (node.Nodes.Count == 0)//leaf
{
if (!node.Value.TrimEnd().Contains('#'))
{
GroupDetails grp_d = new GroupDetails();
grp_d.Boss_code = 0;
grp_d.Boss_name = string.Empty;
if (node.Value.TrimEnd().Split('_').Count() > 2)
{
grp_d.Boss_code = int.Parse(node.Value.TrimEnd().Split('_')[2]);
grp_d.Boss_name = node.Value.TrimEnd().Split('_')[3];
}
grp_d.Dep_code = int.Parse(node.Value.TrimEnd().Split('_')[0]);
grp_d.Dep_name = node.Text.TrimEnd() //Here i want to get the second parent text to concatenate
grp_d.Dep_year = int.Parse(node.Value.TrimEnd().Split('_')[1]);
grp_d.Group_id = res;
grp_det.Add(grp_d);
}
}
}
while( node.parent != null )
node = node.parent;
return node.child;
Assuming you only have one child (i.e. node (2))
Just suggesting a logical way of traversing the tree. Implementation is up to you and your system design!
RadTreeNode node_tmp = new RadTreeNode();
node_tmp = node;
while (node_tmp.ParentNode != null)
{
p_txt = node_tmp.Text.TrimEnd();
node_tmp = node_tmp.ParentNode;
}
Related
I'm working with an alternate version of the BinaryTree class called RedBlackTree. I'm trying to build the tree with this add method.
public void Add(T val)
{
RedBlackNode<T> newNode = _rootNode;
while(newNode != null)
{
if(val.CompareTo(newNode.Data) < 0)
{
newNode = newNode.LeftChild;
}
else if(val.CompareTo(newNode.Data) >= 0)
{
newNode = newNode.RightChild;
}
}
newNode.Data = val; //nullReferenceException thrown here <---
newNode.IsBlack = false;
FixColors(newNode);
}
_rootNode is a private field giving the root of the tree. It is initialized to null as given by specific instructions. This Add method is being called from within another class from a method that is reading in file info. On the first iteration, a nullReferenceException is thrown, I assume because the node I am trying to change is null. I don't know how else I am supposed to change the data value of these nodes. I will post the code to the rest of the program if necessary.
Well, the while loop isn't going to exit while newNode isn't null. That implies newNode is going to be null once the loop exits. I think what you want is to create a new node if the RightChild or LeftChild nodes is null, and set newNode to that.
In addition, as Partha's answer points out, you need to initialize the _rootNode value if it isn't already set.
I don't really know how the parent property of the node is set, so I'm going to assume the parent node is injected as a constructor argument of the child node:
public void Add(T val)
{
RedBlackNode<T> parent = _rootNode;
RedBlackNode<T> target = null;
while(target == null)
{
if(val.CompareTo(parent.Data) < 0)
{
if (parent.LeftChild == null)
target = parent.LeftChild = new RedBlackNode<T>(parent);
else
parent = parent.LeftChild;
}
else if(val.CompareTo(newNode.Data) >= 0)
{
if (parent.RightChild == null)
target = parent.RightChild = new RedBlackNode<T>(parent);
else
parent = parent.RightChild;
}
}
target.Data = val;
target.IsBlack = false;
FixColors(newNode);
}
You need to create the node before you access the other fields. So if _rootNode is empty you create using new keyword.
public void Add(T val)
{
if(_rootNode == null)
{
RedBlackNode<T> newNode = new RedBlackNode<T>();
newNode.Data = val;
newNode.IsBlack = false;
_rootNode = newNode;
return;
}
//Followed by your logic
}
My delete function doesn't work when I try to delete node with only right child. It works when node has left child only or has both left and right.
I would like to know if this is a valid approach to this problem. I know how to write this in C++ but I need it to work in C# also.
//Private method, with args: root node, node to be deleted
private Node DeleteN(Node root, Node deleteNode)
{
if (root == null)
{
return root;
}
if (deleteNode.data < root.data)
{
root.left = DeleteN(root.left, deleteNode);
}
if (deleteNode.data > root.data)
{
root.right = DeleteN(root.right, deleteNode);
}
if (deleteNode.data == root.data)
{
//No child nodes
if (root.left == null && root.right == null)
{
root = null;
return root;
}
//No left child - DONT WORK
else if (root.left == null)
{
Node temp = root;
root = root.right;
temp = null;
}
//No right child
else if (root.right == null)
{
Node temp = root;
root = root.left;
temp = null;
}
//Has both child nodes
else
{
Node min = FindMin2(root.right);
root.data = min.data;
root.right = DeleteN(root.right, min);
}
}
return root;
}
//Public method with arg: int value of node to be deleted
public void DeleteNode(int x)
{
Node deleteNode = new Node(x);
DeleteN(root, deleteNode);
}
Actually, your code works. I have deleted else in case of no left child and I had only an if statement following if statement so it was unreachable,
//No child nodes
if (root.left == null && root.right == null)
{
root = null;
return root;
}
//No left child - DONT WORK
else if (root.left == null) //WORKS NOW-missed else, it has been only if
{
Node temp = root;
root = root.right;
temp = null;
}
//No right child
else if (root.right == null)
{
Node temp = root;
root = root.left;
temp = null;
}
I would like to change the order of System.Windows.Forms.TreeNodes on the same level.
any suggestions on how this might be done in .net-2.0.
You need to manipulate the TreeView's Nodes collection. See TreeNodeCollection.
If you have three tree nodes and you want to move the last one to the front, for example: (Note: not tested code, but shows the idea)
var lastNode = MyTreeView.Nodes[2];
MyTreeView.Nodes.Remove(lastNode);
MyTreeView.Nodes.Insert(0, lastNode);
void MoveNodeUp(TreeNode node)
{
TreeNode parentNode = node.Parent;
int originalIndex = node.Index;
if (node.Index == 0) return;
TreeNode ClonedNode = (TreeNode)node.Clone();
node.Remove();
parentNode.Nodes.Insert(originalIndex - 1, ClonedNode);
parentNode.TreeView.SelectedNode = ClonedNode;
}
That's what I've written:
public void MoveNode(TreeView tv, TreeNode node, bool up)
{
if ((node.PrevNode == null) && up) {
return;
}
if ((node.NextNode == null) && !up) {
return;
}
int newIndex = up ? node.Index - 1 : node.Index + 1;
var nodes = tv.Nodes;
if (node.Parent != null) {
nodes = node.Parent.Nodes;
}
nodes.Remove(node);
nodes.Insert(newIndex, node);
}
I wrote this code which does not require any cloning.
For my case it moves up one position in the sibling nodes but can be adapted
TreeNode selectedNode = treeViewChain.SelectedNode;
if (selectedNode != null && selectedNode.Index > 0)
{
TreeNode parent = selectedNode.Parent;
int selectedIndex = selectedNode.Index;
selectedNode.Remove();
parent.Nodes.Insert(selectedIndex - 1, selectedNode);
treeViewChain.SelectedNode = selectedNode;
}
Having a tree (logical in DB) with items in the form
List item A
List item B
List item C
List item D
List Item E
List Item F
List Item G
and so on (nesting depth not limited), I want to get the next node down (or up), starting from an arbitrary node.
Let's say, List Item D is given I want to write a function GetNextNode() that would return List Item E.
My idea would be to do some recursion stuff, but maybe there is a more clever way to handle this?
My question:
How would you solve this?
EDIT 1:
The tree can be accessed with functions like:
GetParentNode()
GetChildrenNodes()
GetNextSiblingNode()
etc.
So it's similar to e.g. e Windows Forms TreeView.
I've had to do this several times. From memory:
public Node GetBelowNode()
{
if (GetChildrenNodes().count > 0)
return GetChildrenNodes()[0];
else
if (GetNextSiblingNode() != null)
return GetNextSiblingNode();
else
{
Node curr = this;
Node parent;
while (true)
{
parent = curr.GetParentNode();
if (parent == null)
return null;
else
{
if (parent.GetNextSiblingNode() != null)
return parent.GetNextSiblingNode();
else
curr = parent;
}
}
}
}
You can handle this via recursion or... worst xD
I think there are only 3 basic cases:
private string getNext(TreeNode node)
{
if (node.FirstNode != null)
{
return node.FirstNode.Name;
}
else
{
if (node.NextNode != null)
{
return node.NextNode.Name;
}
else if (node.Parent.NextNode != null)
{
return node.Parent.NextNode.Name;
}
}
return "";
}
This doesn't works for every scenario. You should search the parent's next node too. Thanks to Vincent Vancalbergh for the comment ;-)
public Party Next {
get {
if (this.children.Count > 0) return this.children[0];
Party target = this;
do {
if (target.NextSibling != null) return target.NextSibling;
} while ((target = target.Parent) != null);
return null;
}
}
public Party Previous {
get {
if (Parent != null && Parent.children.Count > 0 && this == Parent.children[0]) {
return Parent;
}
Party target = this;
do {
if (target.PreviousSibling != null) { target = target.PreviousSibling; break; }
} while ((target = target.Parent) != null);
if (target != null) {
while (target.children.Count > 0) {
target = target.children[target.children.Count - 1];
}
}
return target;
}
}
Since I got a great reply for the "down" part, I'll added my own "up" part. Maybe it is for some help of you; the up part is similar to:
Get the previous sibling.
If there is a previous sibling, get the deepest child node of this
sibling.
If there is no previous sibling, get the direct parent.
To get the deepest sibling (2.), I use the following code:
function getDeepestChild( page )
dim result
set result = nothing
dim childPages
set childPages = page.ChildPages
if childPages.Count>0 then
dim p
set p = childPages(childPages.Count-1)
' recurse.
set result = getDeepestChild( p )
else
set result = page
end if
set getDeepestChild = result
end function
(Yes, I do know that this is VBScript; I needed it in fact in this language)
Try this maybe:
TreeNode currentNode = treeView1.SelectedNode;
treeView1.selectedNode = currentNode.NextNode;
I am writing a single linked list in C#, could you please suggest to me if there any way to write a better remove method than the one I have:
using System;
class Node
{
public int data = int.MinValue;
public Node m_NextNode;
public Node(int data_in)
{
data = data_in;
}
public Node()
{
}
}
class LinkedList
{
private Node m_HeadNode;
public void InsertData(int data)
{
Node aCurrentNode = m_HeadNode;
if(m_HeadNode == null)
{
m_HeadNode = new Node();
m_HeadNode.data = data;
}
else
{
while(aCurrentNode.m_NextNode != null)
aCurrentNode = aCurrentNode.m_NextNode;
aCurrentNode.m_NextNode = new Node();
aCurrentNode.m_NextNode.data = data;
}
}
public void DisplayData()
{
Node aCurrentNode = m_HeadNode;
while (aCurrentNode != null)
{
Console.WriteLine("the value is {0}", aCurrentNode.data);
aCurrentNode = aCurrentNode.m_NextNode;
}
}
public void RemoveData(int data)
{
Node aCurrentNode = m_HeadNode;
while (aCurrentNode != null)
{
//if the data is present in head
//remove the head and reset the head
if (m_HeadNode.data == data)
{
m_HeadNode = null;
m_HeadNode = aCurrentNode.m_NextNode;
}
else
{
//else save the previous node
Node previousNode = aCurrentNode;
if (aCurrentNode != null)
{
//store the current node
Node NextNode = aCurrentNode.m_NextNode;
if (NextNode != null)
{
//store the next node
Node tempNode = NextNode.m_NextNode;
if (NextNode.data == data)
{
previousNode.m_NextNode = tempNode;
NextNode = null;
}
}
aCurrentNode = aCurrentNode.m_NextNode;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
LinkedList aLinkedList = new LinkedList();
aLinkedList.InsertData(10);
aLinkedList.InsertData(20);
aLinkedList.InsertData(30);
aLinkedList.InsertData(40);
aLinkedList.DisplayData();
aLinkedList.RemoveData(10);
aLinkedList.RemoveData(40);
aLinkedList.RemoveData(20);
aLinkedList.RemoveData(30);
aLinkedList.DisplayData();
Console.Read();
}
}
I would pull the 'if removing the head node' out of the while loop, and make the while loop simpler. Just keep track of the current and previous nodes, and switch the reference when you find the node to remove.
public void RemoveData(int data)
{
if (m_HeadNode == null)
return;
if (m_HeadNode.data == data)
{
m_HeadNode = m_HeadNode.m_NextNode;
}
else
{
Node previous = m_HeadNode;
Node current = m_HeadNode.m_NextNode;
while (current != null)
{
if (current.data == data)
{
// If we're removing the last entry in the list, current.Next
// will be null. That's OK, because setting previous.Next to
// null is the proper way to set the end of the list.
previous.m_NextNode = current.m_NextNode;
break;
}
previous = current;
current = current.m_NextNode;
}
}
}
Is RemoveData supposed to remove one instance of that integer from the list, or all instances? The previous method removes just the first one, here's one that removes all of them.
public void RemoveAllData(int data)
{
while (m_HeadNode != null && m_HeadNode.data == data)
{
m_HeadNode = m_HeadNode.m_NextNode;
}
if(m_HeadNode != null)
{
Node previous = m_HeadNode;
Node current = m_HeadNode.m_NextNode;
while (current != null)
{
if (current.data == data)
{
// If we're removing the last entry in the list, current.Next
// will be null. That's OK, because setting previous.Next to
// null is the proper way to set the end of the list.
previous.m_NextNode = current.m_NextNode;
// If we remove the current node, then we don't need to move
// forward in the list. The reference to previous.Next, below,
// will now point one element forward than it did before.
}
else
{
// Only move forward in the list if we actually need to,
// if we didn't remove an item.
previous = current;
}
current = previous.m_NextNode;
}
}
}
You have a line you do not need:
m_HeadNode = null;
m_HeadNode = aCurrentNode.m_NextNode;
You don't need to set m_HeadNode to null before you set it to something else.
public bool RemoveNode(int data) {
Node prev = null;
for (Node node = head; node != null; node = node.next) {
if (node.data == data) {
if (prev == null) head = node.next;
else prev.next = node.next;
return true;
}
prev = node;
}
return false;
}
public void RemoveData(int data)
{
if(null == m_HeadNode) return;
if(m_HeadNode.data == data)
{
// remove first node
}
else
{
Node current = m_HeadNode;
while((null != current.m_NextNode) && (current.m_NextNode.data != data))
current = current.m_NextNode;
if(null != current.m_NextNode)
{
// do remove node (since this sounds like homework, I'll leave that to you)
}
}
}
with only one local variable.
There is a bug in you code, imagine you have list that has 3 elements with data = 5 and you want to remove 5, you codes stores the head in aCurrentNode and starts the loop. There the condition is true so you move the head to the next. but aCurrentNode is not updated so in the next iteration it's pointing to the previous Head and aCurrentNode.m_NextNod would be your current Head, Hence you got yourself in a never ending loop!
public void Remove(int data)
{
for(var cur = new Node {Next = Head}; cur.Next != null; cur = cur.Next)
{
if (cur.Next.Data != data) continue;
if (cur.Next == Head)
Head = Head.Next;
else
cur.Next = cur.Next.Next;
}
}
a trick to make you loop simpler is to start with a fake node that points to head. This way you don't need to place an If to check head differently, however you need an if to set the head. the other trick is to check for next nodes data. that way you don't need to keep a previous Node.
public SLElement Remove(int index)
{
SLElement prev = _root;
if (prev == null) return null;
SLElement curr = _root._next;
for (int i = 1; i < index; i++)
{
if (curr == null) return null;
prev = curr;
curr = curr._next;
}
prev._next = curr._next;
curr._next = null;
return curr;
}
This deletes the element with a specific index, not with a specific value.
To Make really simple. Please follow the link. Below is a code snippet to remove item from a single link list.
public void DeleteNode(int nodeIndex)
{
int indexCounter = 0;
Node TempNode = StartNode;
Node PreviousNode = null;
while (TempNode.AddressHolder != null)
{
if (indexCounter == nodeIndex)
{
PreviousNode.AddressHolder = TempNode.AddressHolder;
break;
}
indexCounter++;
PreviousNode = TempNode;
TempNode = TempNode.AddressHolder;
}
}