All Topics  
Tree traversal

 

   Email Print
   Bookmark   Link






 

Tree traversal



 
 
In computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
, tree-traversal refers to the process of visiting (examining and/or updating) each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. The following algorithms are described for a binary tree
Binary tree

In computer science, a binary tree is a Tree in which each node has at most two child node. Typically the child nodes are called left and right....
, but they may be generalized to other trees as well.

ared to linear data structures
List of data structures

This is a list of data structures. For a wider list of terms, see list of terms relating to algorithms and data structures.Base Data Structures...
 like linked lists and one dimensional arrays, which have only one logical means of traversal, tree structures can be traversed in many different ways.






Discussion
Ask a question about 'Tree traversal'
Start a new discussion about 'Tree traversal'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
, tree-traversal refers to the process of visiting (examining and/or updating) each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. The following algorithms are described for a binary tree
Binary tree

In computer science, a binary tree is a Tree in which each node has at most two child node. Typically the child nodes are called left and right....
, but they may be generalized to other trees as well.

Traversal

Compared to linear data structures
List of data structures

This is a list of data structures. For a wider list of terms, see list of terms relating to algorithms and data structures.Base Data Structures...
 like linked lists and one dimensional arrays, which have only one logical means of traversal, tree structures can be traversed in many different ways. Starting at the root of a binary tree, there are three main steps that can be performed and the order in which they are performed define the traversal type. These steps (in no particular order) are: performing an action on the current node (referred to as "visiting" the node), traversing to the left child node, and traversing to the right child node. Thus the process is most easily described through recursion
Recursion

Recursion, in mathematics and computer science, is a method of defining Function in which the function being defined is applied within its own definition....
.

To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node:
  1. Visit the root.
  2. Traverse the left subtree.
  3. Traverse the right subtree.
(This is also called Depth-first traversal.)

To traverse a non-empty binary tree in inorder, perform the following operations recursively at each node:
  1. Traverse the left subtree.
  2. Visit the root.
  3. Traverse the right subtree.
(This is also called Symmetric traversal.)

To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node:
  1. Traverse the left subtree.
  2. Traverse the right subtree.
  3. Visit the root.


Finally, trees can also be traversed in level-order, where we visit every node on a level before going to a lower level. This is also called Breadth-first traversal.

Example

In this binary search tree
Binary search tree

In computer science, a binary search tree is a binary tree data structurewhich has the following properties:* Each node has a distinct value....
,
  • Preorder traversal sequence: F, B, A, D, C, E, G, I, H (root,left child,right child)
  • Inorder traversal sequence: A, B, C, D, E, F, G, H, I (leftchild,rootnode,right node)
    • Note that the inorder traversal of this binary search tree yields an ordered list
  • Postorder traversal sequence: A, C, E, D, B, H, I, G, F (leftnode,rightnode,rootnode)
  • Level-order traversal sequence: F, B, G, A, D, I, C, E, H


Sample implementations


preorder(node) print node.value if node.left ? null then preorder(node.left) if node.right ? null then preorder(node.right)

inorder(node) if node.left ? null then inorder(node.left) print node.value if node.right ? null then inorder(node.right)

postorder(node) if node.left ? null then postorder(node.left) if node.right ? null then postorder(node.right) print node.value

All sample implementations will require stack space proportional to the height of the tree. In a poorly balanced tree, this can be quite considerable.

We can remove the stack requirement by maintaining parent pointers in each node, or by threading the tree
Threaded binary tree

A threaded binary tree may be defined as follows:A binary tree is threaded by making all right child pointers, that would normally be null, point to the inorder successor of the node, and all left child pointers, that would normally be null, point to the inorder predecessor of the node."...
. In the case of using threads, this will allow for greatly improved inorder traversal, although retrieving the parent node required for preorder and postorder traversal will be slower than a simple stack based algorithm.

To traverse a threaded tree inorder, we could do something like this:

inorder(node) while hasleftchild(node) do node = node.left do visit(node) if (hasrightchild(node)) then node = node.right while hasleftchild(node) do node = node.left else while node.parent ? null and node = node.parent.right node = node.parent node = node.parent while node ? null

Note that a threaded binary tree will provide a means of determining whether a pointer is a child, or a thread. See threaded binary tree
Threaded binary tree

A threaded binary tree may be defined as follows:A binary tree is threaded by making all right child pointers, that would normally be null, point to the inorder successor of the node, and all left child pointers, that would normally be null, point to the inorder predecessor of the node."...
s for more information.

Level order traversal


Level order traversal is a traversal method by which levels are visited successively starting with level 0 (the root node), and nodes are visited from left to right on each level.

This is commonly implemented using a queue data structure with the following steps (and using the tree below as an example):

Binary Tree


Step 1: Push the root node onto the queue (node 2):

New queue: 2- - - - - - - - - -

Step 2:

Pop the node off the front of the queue (node 2).

Push that node's left child onto the queue (node 7).

Push that node's right child onto the queue (node 5).

Output that node's value (2).

New queue: 7-5- - - - - - - - - Output: 2

Step 3:

Pop the node off the front of the queue (node 7).

Push that node's left child onto the queue (node 2).

Push that node's right child onto the queue (node 6).

Output that node's value (7).

New queue: 5-2-6- - - - - - - - Output: 2 7

Step 4:

Pop the node off the front of the queue (node 5).

Push that node's left child onto the queue (NULL, so take no action).

Push that node's right child onto the queue (node 9).

Output that node's value (5).

New queue: 2-6-9- - - - - - - - Output: 2 7 5

Step 5:

Pop the node off the front of the queue (node 2).

Push that node's left child onto the queue (NULL, so take no action).

Push that node's right child onto the queue (NULL, so take no action).

Output that node's value (2).

New queue: 6-9- - - - - - - - - Output: 2 7 5 2

Step 6:

Pop the node off the front of the queue (node 6).

Push that node's left child onto the queue (node 5).

Push that node's right child onto the queue (node 11).

Output that node's value (6).

New queue: 9-5-11- - - - - - - - Output: 2 7 5 2 6

Step 7:

Pop the node off the front of the queue (node 9).

Push that node's left child onto the queue (node 4).

Push that node's right child onto the queue (NULL, so take no action).

Output that node's value (9).

New queue: 5-11-4- - - - - - - - Output: 2 7 5 2 6 9

Step 8: You will notice that because the remaining nodes in the queue have no children, nothing else will be added to the queue, so the nodes will just be popped off and output consecutively (5, 11, 4). This gives the following:

Final output: 2 7 5 2 6 9 5 11 4

which is a level-order traversal of the tree.

Queue-based level order traversal


Also, listed below is pseudocode for a simple queue based level order traversal, and will require space proportional to the maximum number of nodes at a given depth. This can be as much as the total number of nodes / 2. A more space-efficient approach for this type of traversal can be implemented using an iterative deepening depth-first search
Iterative deepening depth-first search

Iterative deepening depth-first search is a state space search strategy in which a depth-limited search is run repeatedly, increasing the depth limit with each iteration until it reaches , the depth of the shallowest goal state....
.

levelorder(root) q = empty queue q.enqueue(root) while not q.empty do node := q.dequeue visit(node) if node.left ? null q.enqueue(node.left) if node.right ? null q.enqueue(node.right)

Uses


Inorder traversal

It is particularly common to use an inorder traversal on a binary search tree
Binary search tree

In computer science, a binary search tree is a binary tree data structurewhich has the following properties:* Each node has a distinct value....
 because this will return values from the underlying set in order, according to the comparator that set up the binary search tree (hence the name).

To see why this is the case, note that if n is a node in a binary search tree, then everything in n 's left subtree is less than n, and everything in n 's right subtree is greater than or equal to n. Thus, if we visit the left subtree in order, using a recursive call, and then visit n, and then visit the right subtree in order, we have visited the entire subtree rooted at n in order. We can assume the recursive calls correctly visit the subtrees in order using the mathematical principle of structural induction
Structural induction

Structural induction is a proof method that is used in mathematical logic , computer science, graph theory, and some other mathematical fields. It is a generalization of mathematical induction....
. Traversing in reverse inorder similarly gives the values in decreasing order.

Preorder traversal

Traversing a tree in preorder while inserting the values into a new tree is common way of making a complete copy of a binary search tree
Binary search tree

In computer science, a binary search tree is a binary tree data structurewhich has the following properties:* Each node has a distinct value....
.

One can also use preorder traversals to get a prefix expression (Polish notation
Polish notation

Polish notation, also known as prefix notation, is a form of notation for logic, arithmetic, and algebra. Its distinguishing feature is that it places operators to the left of their operands....
) from expression trees: traverse the expression tree preorderly. To calculate the value of such an expression: scan from right to left, placing the elements in a stack
Stack

Stack may refer to:...
. Each time we find an operator, we replace the two top symbols of the stack with the result of applying the operator to those elements. For instance, the expression * + 2 3 4, which in infix notation is (2 + 3) * 4, would be evaluated like this:

Functional traversal

We could perform the same traversals in a functional language like Haskell
Haskell (programming language)

Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:...
 using code similar to this:

data Tree a = Nil | Node (Tree a) a (Tree a)

preorder Nil = [] preorder (Node left x right) = [x] ++ (preorder left) ++ (preorder right)

postorder Nil = [] postorder (Node left x right) = (postorder left) ++ (postorder right) ++ [x]

inorder Nil = [] inorder (Node left x right) = (inorder left) ++ [x] ++ (inorder right)

Iterative traversing

All the above recursive algorithms require stack space proportional to the depth of the tree. Recursive traversal may be converted into an iterative one using various well-known methods.

A sample is shown here for postorder traversal using a visited flag:

nonRecursivePostorder(rootNode) nodeStack.push(rootNode) while (! nodeStack.empty) currNode = nodeStack.peek if ((currNode.left != null) and (currNode.left.visited

false)) nodeStack.push(currNode.left) else if ((currNode.right != null) and (currNode.right.visited

false)) nodeStack.push(currNode.right) else print currNode.value currNode.visited := true nodeStack.pop

In this case, for each node is required to keep an additional "visited" flag, other than usual informations (value, left-child-reference, right-child-reference).

Another example is preorder traversal without using a visited flag (Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
): public void traverseTree(Node root)

See also

  • Tree programming
    Tree programming

    Tree programming refers to the use of a programming language to analyze Tree , in a way unique from conventional programming languages. This should not be confused with list-based programming languages like Lisp and Scheme ....
  • Polish notation
    Polish notation

    Polish notation, also known as prefix notation, is a form of notation for logic, arithmetic, and algebra. Its distinguishing feature is that it places operators to the left of their operands....
  • Depth-first search
    Depth-first search

    Depth-first search is an algorithm for traversing or searching a tree data structure, tree structure, or graph . One starts at the root and explores as far as possible along each branch before backtracking....
  • Breadth-first search
    Breadth-first search

    In graph theory, breadth-first search is a graph search algorithm that begins at the root node and explores all the neighboring nodes. Then for each of those nearest nodes, it explores their unexplored neighbor nodes, and so on, until it finds the goal....
  • Threaded binary tree
    Threaded binary tree

    A threaded binary tree may be defined as follows:A binary tree is threaded by making all right child pointers, that would normally be null, point to the inorder successor of the node, and all left child pointers, that would normally be null, point to the inorder predecessor of the node."...
     - linear traversal of binary tree
  • Nested set model
    Nested set model

    A nested set model is a way of organising hierarchical data in a relational database. The underlying mathematics is based on the graph theory and set theory....


External links

  • with traversal examples in PHP