private void DriveRemoveHalfNodes() { var classRef = new RemHalfNodes<int>(); var treeBuilder = new TreeBuilder(); var treeTraversal = new TreeTraversal<int>(); var root = treeBuilder.BootStrapTree5(); var newRoot = classRef.RemoveNodes(ref root); treeTraversal.PreOrder(newRoot); Console.WriteLine(); root = treeBuilder.BootStrapTree1(); newRoot = classRef.RemoveNodes(ref root); treeTraversal.PreOrder(newRoot); Console.WriteLine(); root = treeBuilder.BootStrapTree2(); newRoot = classRef.RemoveNodes(ref root); treeTraversal.PreOrder(newRoot); Console.WriteLine(); root = treeBuilder.BootStrapTree3(); newRoot = classRef.RemoveNodes(ref root); treeTraversal.PreOrder(newRoot); Console.WriteLine(); }
public ITreeNode[] Find(object obj, TreeTraversal traversal) { if (this.proot == null) { return null; } ArrayList ary = new ArrayList(); this.Traversal(this.Root, traversal, obj, true, ref ary); return (ITreeNode[]) ary.ToArray(typeof(ITreeNode)); }
private IEnumerable <T> FindReferencesInTypeScope(CancellationToken ct) { foreach (TypeDefinition type in TreeTraversal.PreOrder(typeScope, t => t.NestedTypes)) { ct.ThrowIfCancellationRequested(); foreach (var result in typeAnalysisFunction(type)) { ct.ThrowIfCancellationRequested(); yield return(result); } } }
private IEnumerable <T> FindReferencesInAssembly(AssemblyDefinition asm, CancellationToken ct) { foreach (TypeDefinition type in TreeTraversal.PreOrder(asm.MainModule.Types, t => t.NestedTypes)) { ct.ThrowIfCancellationRequested(); foreach (var result in typeAnalysisFunction(type)) { ct.ThrowIfCancellationRequested(); yield return(result); } } }
public void TreeFindMax() { TreeTraversal <string> t = new TreeTraversal <string>(); string[] patterns = new[] { "A", "M", "P", "L", "E" }; TreeNode <string> max = t.Max(patterns, 0, patterns.Length - 1); Assert.AreEqual("P", max.Item); patterns = new[] { "recursive", "program", "that", "builds", "a", "tournament" }; max = t.Max(patterns, 0, patterns.Length - 1); Assert.AreEqual("tournament", max.Item); }
public double TotalExtentSum() { double extSum = 0; TreeTraversal t = new TreeTraversal() { NextBoxF = (box, depth) => { extSum += box.Extents.LengthL1; return(true); } }; DoTraversal(t); return(extSum); }
public AttributeStore(ICompilation compilation, IErrorReporter errorReporter) { _errorReporter = errorReporter; _assemblyStore = new Dictionary <IAssembly, AttributeList>(); _entityStore = new Dictionary <IEntity, AttributeList>(); _assemblyTransformers = new List <Tuple <IAssembly, PluginAttributeBase> >(); _entityTransformers = new List <Tuple <IEntity, PluginAttributeBase> >(); foreach (var a in compilation.Assemblies) { ReadAssemblyAttributes(a, _assemblyTransformers); } foreach (var t in compilation.Assemblies.SelectMany(a => TreeTraversal.PostOrder(a.TopLevelTypeDefinitions, t => t.NestedTypes))) { foreach (var m in t.Methods) { ReadEntityAttributes(m, _entityTransformers); } foreach (var p in t.Properties) { if (p.CanGet) { ReadEntityAttributes(p.Getter, _entityTransformers); } if (p.CanSet) { ReadEntityAttributes(p.Setter, _entityTransformers); } ReadEntityAttributes(p, _entityTransformers); } foreach (var f in t.Fields) { ReadEntityAttributes(f, _entityTransformers); } foreach (var e in t.Events) { if (e.CanAdd) { ReadEntityAttributes(e.AddAccessor, _entityTransformers); } if (e.CanRemove) { ReadEntityAttributes(e.RemoveAccessor, _entityTransformers); } ReadEntityAttributes(e, _entityTransformers); } ReadEntityAttributes(t, _entityTransformers); } }
public double TotalVolume() { double volSum = 0; TreeTraversal t = new TreeTraversal() { NextBoxF = (box, depth) => { volSum += box.Volume; return(true); } }; DoTraversal(t); return(volSum); }
public void Traverse(TreeTraversal order) { if (order == TreeTraversal.InOrder) { InOrder(_rootNode); } else if (order == TreeTraversal.PreOrder) { PreOrder(_rootNode); } else if (order == TreeTraversal.PostOrder) { PostOrder(_rootNode); } }
public void TreeTraversal_ReverseIteration_DFS_Works() { var forwards = TreeTraversal <TestTreePart> .All(root, eTraversalFlowDirection.ThroughChildren, eTraversalStrategy.DepthFirst).Select(_ => _.Value).ToList(); var backwards = TreeTraversal <TestTreePart> .All(end, eTraversalFlowDirection.ReversedThroughChildren, eTraversalStrategy.DepthFirst).Select(_ => _.Value).ToList(); backwards.Reverse(); Assert.AreEqual(forwards.Count, backwards.Count); for (int index = 0; index < forwards.Count; ++index) { Assert.AreEqual(forwards[index], backwards[index]); } }
// traversal implementation. you can override to customize this if necessary. protected virtual void tree_traversal(int iBox, int depth, TreeTraversal traversal) { int idx = box_to_index[iBox]; if (idx < points_end) { // point-list case, array is [N t1 t2 ... tN] int n = index_list[idx]; for (int i = 1; i <= n; ++i) { int ti = index_list[idx + i]; if (PointFilterF != null && PointFilterF(ti) == false) { continue; } traversal.NextPointF(ti); } } else { int i0 = index_list[idx]; if (i0 < 0) { // negative index means we only have one 'child' box to descend into i0 = (-i0) - 1; if (traversal.NextBoxF(get_box(i0), depth + 1)) { tree_traversal(i0, depth + 1, traversal); } } else { // positive index, two sequential child box indices to descend into i0 = i0 - 1; if (traversal.NextBoxF(get_box(i0), depth + 1)) { tree_traversal(i0, depth + 1, traversal); } int i1 = index_list[idx + 1] - 1; if (traversal.NextBoxF(get_box(i1), depth + 1)) { tree_traversal(i1, depth + 1, traversal); } } } }
/// <summary> /// Breadth First search of the document tree /// </summary> public JsonValue FindValueByKey(string key, eTraversalStrategy strategy = eTraversalStrategy.BreadthFirst, eTraversalFlowDirection direction = eTraversalFlowDirection.ThroughChildren) { JsonValue found = TreeTraversal <JsonValue> .GetFirstChildWhichPasses(this, _TestIsDocumentWithKey, direction, strategy); if (found != null) { return(((JsonDocument)found).ValueFor(key)); } return(null); bool _TestIsDocumentWithKey(JsonValue value) { return(value.IsDocument && ((JsonDocument)value).ContainsKey(key)); } }
protected void CollectTreeNodes(TreeNodeCollection treeNodes, TreeTraversal treeTraversal) { Debug.Assert(treeNodes != null); if (treeTraversal == TreeTraversal.PreFix) { treeNodes.Add(this); } foreach (TreeNode treeNode in _treeNodes) { treeNode.CollectTreeNodes(treeNodes, treeTraversal); } if (treeTraversal == TreeTraversal.PostFix) { treeNodes.Add(this); } }
// do full tree traversal below iBox to make sure that all child points are contained void debug_check_child_points_in_box(int iBox) { AxisAlignedBox3d box = get_box(iBox); TreeTraversal t = new TreeTraversal() { NextPointF = (vID) => { Vector3d v = points.GetVertex(vID); if (box.Contains(v) == false) { Util.gBreakToDebugger(); } } }; tree_traversal(iBox, 0, t); }
/// <summary> /// Given a natural loop, add additional CFG nodes to the loop in order /// to reduce the number of exit points out of the loop. /// We do this because C# only allows reaching a single exit point (with 'break' /// statements or when the loop condition evaluates to false), so we'd have /// to introduce 'goto' statements for any additional exit points. /// </summary> /// <remarks> /// Definition: /// A "reachable exit" is a branch/leave target that is reachable from the loop, /// but not dominated by the loop head. A reachable exit may or may not have a /// corresponding CFG node (depending on whether it is a block in the current block container). /// -> reachable exits are leaving the code region dominated by the loop /// /// Definition: /// A loop "exit point" is a CFG node that is not itself part of the loop, /// but has at least one predecessor which is part of the loop. /// -> exit points are leaving the loop itself /// /// Nodes can only be added to the loop if they are dominated by the loop head. /// When adding a node to the loop, we must also add all of that node's predecessors /// to the loop. (this ensures that the loop keeps its single entry point) /// /// Goal: If possible, find a set of nodes that can be added to the loop so that there /// remains only a single exit point. /// Add as little code as possible to the loop to reach this goal. /// /// This means we need to partition the set of nodes dominated by the loop entry point /// into two sets (in-loop and out-of-loop). /// Constraints: /// * the loop head itself is in-loop /// * there must not be any edge from an out-of-loop node to an in-loop node /// -> all predecessors of in-loop nodes are also in-loop /// -> all nodes in a cycle are part of the same partition /// Optimize: /// * use only a single exit point if at all possible /// * minimize the amount of code in the in-loop partition /// (thus: maximize the amount of code in the out-of-loop partition) /// "amount of code" could be measured as: /// * number of basic blocks /// * number of instructions directly in those basic blocks (~= number of statements) /// * number of instructions in those basic blocks (~= number of expressions) /// (we currently use the number of statements) /// /// Observations: /// * If a node is in-loop, so are all its ancestors in the dominator tree (up to the loop entry point) /// * If there are no exits reachable from a node (i.e. all paths from that node lead to a return/throw instruction), /// it is valid to put the group of nodes dominated by that node into either partition independently of /// any other nodes except for the ancestors in the dominator tree. /// (exception: the loop head itself must always be in-loop) /// /// There are two different cases we need to consider: /// 1) There are no exits reachable at all from the loop head. /// -> it is possible to create a loop with zero exit points by adding all nodes /// dominated by the loop to the loop. /// -> the only way to exit the loop is by "return;" or "throw;" /// 2) There are some exits reachable from the loop head. /// /// In case 1, we can pick a single exit point freely by picking any node that has no reachable exits /// (other than the loop head). /// All nodes dominated by the exit point are out-of-loop, all other nodes are in-loop. /// See PickExitPoint() for the heuristic that picks the exit point in this case. /// /// In case 2, we need to pick our exit point so that all paths from the loop head /// to the reachable exits run through that exit point. /// /// This is a form of postdominance where the reachable exits are considered exit nodes, /// while "return;" or "throw;" instructions are not considered exit nodes. /// /// Using this form of postdominance, we are looking for an exit point that post-dominates all nodes in the natural loop. /// --> a common ancestor in post-dominator tree. /// To minimize the amount of code in-loop, we pick the lowest common ancestor. /// All nodes dominated by the exit point are out-of-loop, all other nodes are in-loop. /// (using normal dominance as in case 1, not post-dominance!) /// /// If it is impossible to use a single exit point for the loop, the lowest common ancestor will be the fake "exit node" /// used by the post-dominance analysis. In this case, we fall back to the old heuristic algorithm. /// /// Requires and maintains the invariant that a node is marked as visited iff it is contained in the loop. /// </remarks> void ExtendLoop(ControlFlowNode loopHead, List <ControlFlowNode> loop, out ControlFlowNode exitPoint) { exitPoint = FindExitPoint(loopHead, loop); Debug.Assert(!loop.Contains(exitPoint), "Cannot pick an exit point that is part of the natural loop"); if (exitPoint != null) { // Either we are in case 1 and just picked an exit that maximizes the amount of code // outside the loop, or we are in case 2 and found an exit point via post-dominance. // Note that if exitPoint == NoExitPoint, we end up adding all dominated blocks to the loop. var ep = exitPoint; foreach (var node in TreeTraversal.PreOrder(loopHead, n => DominatorTreeChildren(n, ep))) { if (!node.Visited) { node.Visited = true; loop.Add(node); } } // The loop/switch can only be entered through the entry point. if (isSwitch) { // In the case of a switch, false positives in the "continue;" detection logic // can lead to falsely excludes some blocks from the body. // Fix that by including all predecessors of included blocks. Debug.Assert(loop[0] == loopHead); for (int i = 1; i < loop.Count; i++) { foreach (var p in loop[i].Predecessors) { if (!p.Visited) { p.Visited = true; loop.Add(p); } } } } Debug.Assert(loop.All(n => n == loopHead || n.Predecessors.All(p => p.Visited))); } else { // We are in case 2, but could not find a suitable exit point. // Heuristically try to minimize the number of exit points // (but we'll always end up with more than 1 exit and will require goto statements). ExtendLoopHeuristic(loopHead, loop, loopHead); } }
static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); TreeTraversal treeTraversal = new TreeTraversal(); treeTraversal.FindLeastCommonAncestor(tree.root, 5, 4); treeTraversal.InOrderIterative(tree.root); treeTraversal.InOrderRecursive(tree.root); }
private IEnumerable <BonsaiNode> LowerPriorityAbortables(BonsaiNode aborter) { GetCompositeParent(aborter, out BonsaiNode parent, out BonsaiNode directChild); if (parent != null) { parent.SortChildren(); int abortIndex = parent.IndexOf(directChild); if (abortIndex >= 0) { return(Enumerable .Range(0, parent.ChildCount()) .Where(i => i > abortIndex) .SelectMany(i => TreeTraversal.PreOrder(parent.GetChildAt(i)))); } } return(Enumerable.Empty <BonsaiNode>()); }
public void GetLowestLeftTerm_Input5ElementTerm_ReturnsFirstAddedTerm() { var kTerm = CombinatorK.ConstructCombinator(); var kTerm1 = CombinatorK.ConstructCombinator(); string name3 = "rumba"; var term3 = new Constant(name3); string name4 = "spinner"; var term4 = new Constant(name4); string name5 = "vape"; var term5 = new Constant(name5); var startingTermsList = new Term[] { kTerm, kTerm1, term3, term4, term5 }; var term = Term.BuildWith(startingTermsList); var result = TreeTraversal.GetLowestLeftNode(term); Assert.AreEqual(result.Stringify(), kTerm.Stringify()); }
private void PopulateItems() { if (ItemsSource == null) { return; } if (ItemTemplate.DataType != null && !ReflectionHelper.IsTypeDerived(ItemTemplate.DataType, GetType())) { LogEvent.UserInterface.Warning(string.Format("ItemTemplate '{0}' expects type {1}. Element '{2}' is of type {3}", ItemTemplate.Key, ItemTemplate.DataType.Name, Name, GetType().Name)); return; } int itemCount = 1; foreach (var item in ItemsSource) { UIElement previousElement = this; foreach (UIElement element in TreeTraversal.PreOrderVisit(ItemTemplate.VisualTree)) { UIElement newItem = ToDispose(element.Copy()); if (element.Parent is ContentControl) { ((ContentControl)previousElement).Content = newItem; } else { container.Add(newItem); } newItem.DataContext = item; foreach (var kvp in ItemTemplate.Bindings.Where(kvp => string.Equals(newItem.Name, kvp.Value.TargetElement))) { newItem.SetBinding(kvp.Value, kvp.Key); } newItem.Name = string.Format("{0}{1:D2}", newItem.Name, itemCount++); previousElement = newItem; } } }
private void TestLinkedListTree(int[] input) { Tree tree = new Tree(); TreeTraversal treeTraversal = new TreeTraversal(); var output = tree.CreateTreeByLinkedList(input); Utility.PrintFiltered(input); treeTraversal.Traverse <int>(TreeIterationType.Iterative, TreeTraversalType.InOrder, output); treeTraversal.Traverse <int>(TreeIterationType.Recursive, TreeTraversalType.InOrder, output); treeTraversal.Traverse <int>(TreeIterationType.Iterative, TreeTraversalType.PreOrder, output); treeTraversal.Traverse <int>(TreeIterationType.Recursive, TreeTraversalType.PreOrder, output); treeTraversal.Traverse <int>(TreeIterationType.Iterative, TreeTraversalType.PostOrder, output); treeTraversal.Traverse <int>(TreeIterationType.Recursive, TreeTraversalType.PostOrder, output); treeTraversal.Traverse <int>(TreeIterationType.Iterative, TreeTraversalType.BreadthFirstOrder, output); treeTraversal.Traverse <int>(TreeIterationType.Recursive, TreeTraversalType.BreadthFirstOrder, output); }
//test case static void Main(string[] args) { var c = new Node <char>('C'); var e = new Node <char>('E'); var h = new Node <char>('H'); var a = new Node <char>('A'); var d = new Node <char>('D', c, e); var i = new Node <char>('I', h); var b = new Node <char>('B', a, d); var g = new Node <char>('G', right: i); var f = new Node <char>('F', b, g); Console.Write("Level order traversal sequence: "); foreach (var x in TreeTraversal.AsBreadthFirst(f)) { Console.Write(x + " "); } Console.WriteLine(); }
// ===============================[ Construction ]=========================== static JsonValue() { JsonValue[] emptyEnumerable = new JsonValue[0]; // Setup tree traversal TreeTraversal <JsonValue> .SetupDefaults( jv => { if (jv.IsDocument) { return(((JsonDocument)jv).AllValues()); } else if (jv.IsArray) { return((JsonArray)jv); } return(emptyEnumerable); }, jv => jv.Parent); }
// traversal implementation private void tree_traversal(int iBox, int depth, TreeTraversal traversal) { int idx = box_to_index[iBox]; if (idx < triangles_end) { // triange-list case, array is [N t1 t2 ... tN] int n = index_list[idx]; for (int i = 1; i <= n; ++i) { int ti = index_list[idx + i]; traversal.NextTriangleF(ti); } } else { int i0 = index_list[idx]; if (i0 < 0) { // negative index means we only have one 'child' box to descend into i0 = (-i0) - 1; if (traversal.NextBoxF(get_box(i0), depth + 1)) { tree_traversal(i0, depth + 1, traversal); } } else { // positive index, two sequential child box indices to descend into i0 = i0 - 1; if (traversal.NextBoxF(get_box(i0), depth + 1)) { tree_traversal(i0, depth + 1, traversal); } int i1 = index_list[idx + 1] - 1; if (traversal.NextBoxF(get_box(i1), depth + 1)) { tree_traversal(i1, depth + 1, traversal); } } } }
// do full tree traversal below iBox to make sure that all child triangles are contained void debug_check_child_tris_in_box(int iBox) { AxisAlignedBox3f box = get_box(iBox); TreeTraversal t = new TreeTraversal() { NextTriangleF = (tID) => { Index3i tv = mesh.GetTriangle(tID); for (int j = 0; j < 3; ++j) { Vector3f v = (Vector3f)mesh.GetVertex(tv[j]); if (box.Contains(v) == false) { Util.gBreakToDebugger(); } } } }; tree_traversal(iBox, 0, t); }
// do full tree traversal below iBox and make sure that all triangles are further // than box-distance-sqr void debug_check_child_tri_distances(int iBox, Vector3d p) { double fBoxDistSqr = box_distance_sqr(iBox, p); TreeTraversal t = new TreeTraversal() { NextTriangleF = (tID) => { double fTriDistSqr = MeshQueries.TriDistanceSqr(mesh, tID, p); if (fTriDistSqr < fBoxDistSqr) { if (Math.Abs(fTriDistSqr - fBoxDistSqr) > MathUtil.ZeroTolerance * 100) { Util.gBreakToDebugger(); } } } }; tree_traversal(iBox, 0, t); }
public IEnumerable <T> GetItems(TreeTraversal treeTraversal) { switch (treeTraversal) { case TreeTraversal.InOrder: return(InOrder(_root)); case TreeTraversal.PreOrder: return(PreOrder(_root)); case TreeTraversal.PostOrder: return(PostOrder(_root)); case TreeTraversal.ReverseInOrder: return(ReverseInOrder(_root)); default: throw new NotSupportedException($"{treeTraversal} is not supported."); } }
void IDesktopOverlay.ProcessKeyDown(KeyEventArgs e) { // If an element as captured the pointer, send the event to it first if (CaptureElement != null) { e.Handled = CaptureElement.ProcessKeyDown(e); } if (e.Handled) { return; } // Then, send it to the currently focused control if (FocusedElement != null) { e.Handled = FocusedElement.ProcessKeyDown(e); } if (e.Handled) { return; } //Proceeds with the rest foreach (UIElement control in TreeTraversal.PostOrderInteractionVisit(this)) { e.Handled = control.ProcessKeyDown(e); if (e.Handled) { break; } } if (e.Handled) { return; } e.Handled = ProcessKeyDown(e); }
private void CreateContainer() { Contract.Requires <InvalidOperationException>(ItemTemplate.VisualTree is Panel, "VisualTree root must be a Panel"); var panel = (Panel)ToDispose(ItemsPanelTemplate.VisualTree.Copy()); if (panel.IsItemsHost) { container = panel; } else { foreach (var child in TreeTraversal.PreOrderVisit(panel)) { var childPanel = child as Panel; if (childPanel != null && childPanel.IsItemsHost) { container = childPanel; break; } } } foreach (var kvp in ItemsPanelTemplate.Bindings) { var target = panel.Find(kvp.Value.TargetElement); if (target != null) { target.DataContext = DataContext; target.SetBinding(kvp.Value, kvp.Key); break; } } if (container == null) { container = panel; } Children.Add(panel); }
/// <summary> /// Gets all base type definitions. /// </summary> /// <remarks> /// This is equivalent to type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct(). /// </remarks> public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type, ITypeResolveContext context) { if (type == null) throw new ArgumentNullException("type"); if (context == null) throw new ArgumentNullException("context"); HashSet<ITypeDefinition> typeDefinitions = new HashSet<ITypeDefinition>(); Func<ITypeDefinition, IEnumerable<ITypeDefinition>> recursion = t => t.GetBaseTypes(context).Select(b => b.GetDefinition()).Where(d => d != null && typeDefinitions.Add(d)); ITypeDefinition typeDef = type as ITypeDefinition; if (typeDef != null) { typeDefinitions.Add(typeDef); return TreeTraversal.PreOrder(typeDef, recursion); } else { return TreeTraversal.PreOrder( type.GetBaseTypes(context).Select(b => b.GetDefinition()).Where(d => d != null && typeDefinitions.Add(d)), recursion); } }
// do full tree traversal below iBox and make sure that all points are further // than box-distance-sqr void debug_check_child_point_distances(int iBox, Vector3d p) { double fBoxDistSqr = box_distance_sqr(iBox, ref p); TreeTraversal t = new TreeTraversal() { NextPointF = (vID) => { Vector3d v = points.GetVertex(vID); double fDistSqr = p.DistanceSquared(v); if (fDistSqr < fBoxDistSqr) { if (Math.Abs(fDistSqr - fBoxDistSqr) > MathUtil.ZeroTolerance * 100) { Util.gBreakToDebugger(); } } } }; tree_traversal(iBox, 0, t); }
public IEnumerable <ITypeDefinition> GetTypesInScope(CancellationToken ct) { if (IsLocal) { foreach (var type in TreeTraversal.PreOrder(typeScope, t => t.NestedTypes)) { yield return(type); } } else { foreach (var module in GetModulesInScope(ct)) { var typeSystem = ConstructTypeSystem(module); foreach (var type in typeSystem.MainModule.TypeDefinitions) { yield return(type); } } } }
/// <summary> /// The set of all nodes in this subtree. /// </summary> /// <param name="mode">The order in which we will travers the nodes in the subtree.</param> /// <returns>The nodes in the subtree.</returns> public IEnumerable <DecompositionNode> SubTree(TreeTraversal mode) { if (mode == TreeTraversal.ParentFirst) { Queue <DecompositionNode> queue = new Queue <DecompositionNode>(); queue.Enqueue(this); while (queue.Count > 0) { DecompositionNode node = queue.Dequeue(); if (!node.IsLeaf) { queue.Enqueue(node.Left); queue.Enqueue(node.Right); } yield return(node); } } else { DecompositionNode finished = this; Stack <DecompositionNode> stack = new Stack <DecompositionNode>(); stack.Push(this); while (stack.Count > 0) { DecompositionNode node = stack.Peek(); if (node.IsLeaf || node.Right == finished) { stack.Pop(); finished = node; yield return(node); } else { stack.Push(node.Right); stack.Push(node.Left); } } } }
public ITreeNode[] Traversal(TreeTraversal traversal) { ArrayList ary = new ArrayList(); this.Traversal(this.Root, traversal, null, false, ref ary); return (ITreeNode[]) ary.ToArray(typeof(ITreeNode)); }
protected virtual void Traversal(ITreeNode node, TreeTraversal traversal, object obj, bool search, ref ArrayList ary) { if (node != null) { ITreeNode firstChild = null; switch (traversal) { case TreeTraversal.PreOrder: if (!search || (search && this.Found(node, obj))) { ary.Add(node); } for (int i = 0; i < node.Degree; i++) { firstChild = (i == 0) ? node.FirstChild : firstChild.NextSibling; if (firstChild != null) { this.Traversal(firstChild, traversal, obj, search, ref ary); } } return; case TreeTraversal.InOrder: if (!node.IsLeafe) { firstChild = node.FirstChild; if (firstChild != null) { this.Traversal(firstChild, traversal, obj, search, ref ary); } if (!search || (search && this.Found(node, obj))) { ary.Add(node); } if (node.Degree <= 1) { break; } for (int j = 1; j < node.Degree; j++) { firstChild = firstChild.NextSibling; if (firstChild != null) { this.Traversal(firstChild, traversal, obj, search, ref ary); } } return; } if (search && (!search || !this.Found(node, obj))) { break; } ary.Add(node); return; case TreeTraversal.PostOrder: for (int k = 0; k < node.Degree; k++) { firstChild = (k == 0) ? node.FirstChild : firstChild.NextSibling; if (firstChild != null) { this.Traversal(firstChild, traversal, obj, search, ref ary); } } if (!search || (search && this.Found(node, obj))) { ary.Add(node); return; } break; default: throw new NotSupportedException(SR.NotSupported); } } }