Traversing a wxTree
Much wxTree processing involves doing the same thing to each node in one branch of the tree. Of course the branch might be the entire tree.
One way of doing this is to split the code for doing this into two functions. One function does what is needed for a single node in the tree and the other function calls the first function passing it one node at a time. The second function is responsible for walking the tree so that the first function also encounters every node. It is said to perform "tree traversal".
One tries to write a tree traversal function in such a way that it can be re-used in combination with other functions to perform a variety of tasks.
One way of doing it
Here is one tree traversal function. To use it, one supplies a function that will be called for each node in the tree (func), the root node of the branch that is to be processed (startNode) and an optional Boolean value indicating whether the root node of the branch is to be processed along with any progeny that it may have (ProcessStartNode).
def Traverse ( self, func, startNode, ProcessStartNode = true ): """Apply 'func' to each node in a branch, beginning with 'startNode'. At each level process the next level down (the children) before processing the nodes at the current level.""" def TraverseAux ( node, depth, func ): nc = self.GetChildrenCount ( node, 0 ) childList = [ ] GetChild = self.GetFirstChild cookie = 1 for i in xrange ( nc ): child, cookie = GetChild ( node, cookie ) GetChild = self.GetNextChild childList.append ( child ) TraverseAux ( child, depth + 1, func ) for child in childList: func ( child, depth ) TraverseAux ( startNode, 0, func ) if ProcessStartNode: func ( startNode, 0 )
Please note that you will need to include the following line very near the beginning of your module.
from __future__ import nested_scopes
Sample use
The following code illustrates how to use Traverse to visit each node in a tree starting with the currently selected node, and applying DeleteOneNode to each node that is visited in this way.
def DeleteOneNode ( self, node, depth ): self.Delete ( node ) ... self.Traverse ( self.DeleteOneNode, self.GetSelected ( ) )
Comments to Bill Bell