private static void RecursiveDeleteNodeChild(KwayTreeNode <T> node) { foreach (KwayTreeNode <T> next in node.Child) { RecursiveDeleteNodeChild(next); next.Child = null; } }
public KwayTreeNode <T> GetNext(int id) { KwayTreeNode <T> node = SearchNode(id, out List <KwayTreeNode <T> > sibling); int idx = sibling.IndexOf(node); if (idx + 1 < sibling.Count) { return(sibling[idx + 1]); } else { return(null); } }
/// <summary> /// Delete node from tree. If success, return true. /// </summary> /// <param name="id"></param> /// <returns></returns> public bool DeleteNode(int id) { // Root NodeList, cannot delete if (id == 0) { return(false); } KwayTreeNode <T> node = SearchNode(id, out List <KwayTreeNode <T> > sibling); Debug.Assert(node != null); Count -= CountLeaves(node); RecursiveDeleteNodeChild(node); sibling.Remove(node); Count--; return(true); }
/// <summary> /// Do not include root node itself. /// </summary> /// <param name="node"></param> /// <returns></returns> public int CountLeaves(KwayTreeNode <T> node) { Queue <List <KwayTreeNode <T> > > q = new Queue <List <KwayTreeNode <T> > >(); int leavesCount = 0; q.Enqueue(node.Child); while (0 < q.Count) { List <KwayTreeNode <T> > next = q.Dequeue(); foreach (KwayTreeNode <T> leaf in next) { leavesCount++; if (0 < leaf.Child.Count) { q.Enqueue(leaf.Child); } } } return(leavesCount); }
/// <summary> /// Add node to tree. Returns node id. If fails, return -1. /// </summary> /// <param name="parentId"></param> /// <param name="data"></param> /// <returns></returns> public int AddNode(int parentId, T data) { if (parentId == 0) { // Root NodeList int id = _idList.Max() + 1; _idList.Add(id); KwayTreeNode <T> node = new KwayTreeNode <T>(parentId, id, data, null); Root.Add(node); Count++; return(id); } else { int id = _idList.Max() + 1; _idList.Add(id); KwayTreeNode <T> parent = SearchNode(parentId); Debug.Assert(parent != null); KwayTreeNode <T> node = new KwayTreeNode <T>(parentId, id, data, parent.Child); parent.Child.Add(node); Count++; return(id); } }
private static KwayTreeNode <T> RecursiveSearchNode(T data, List <KwayTreeNode <T> > list, out List <KwayTreeNode <T> > sibling) { foreach (KwayTreeNode <T> node in list) { if (data.Equals(node.Data)) { sibling = list; return(node); } if (0 < node.Child.Count) { KwayTreeNode <T> res = RecursiveSearchNode(data, node.Child, out sibling); if (res != null) { return(res); } } } // Not found, return null sibling = null; return(null); }
private KwayTreeNode <T> RecursiveSearchNode(int id, List <KwayTreeNode <T> > list, out List <KwayTreeNode <T> > sibling) { foreach (KwayTreeNode <T> node in list) { if (id == node.Id) { sibling = list; return(node); } if (0 < node.Child.Count) { KwayTreeNode <T> res = RecursiveSearchNode(id, node.Child, out sibling); if (res != null) { return(res); } } } // Not found, return null sibling = null; return(null); }