12
08/08/12 Tree traversal - Wikipedia, the free encyclopedia 1/12 en.wikipedia.org/wiki/Tree_traversal Tree traversal From Wikipedia, the free encyclopedia In computer science, 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, but they may be generalized to other trees as well. Contents 1 Traversals 1.1 Depth-first traversal 1.2 Breadth-first traversal 2 Example 3 Infinite trees 4 Implementations 4.1 Queue-based level order traversal 4.2 Uses 4.3 Functional traversal 4.4 Iterative Traversal 4.5 Recursive Traversals in C 4.5.1 Inorder Traversal 4.5.2 Preorder Traversal 4.5.3 Postorder Traversal 5 References 6 External links Traversals Compared to linear data structures like linked lists and one dimensional arrays, which have a canonical method of traversal (namely in linear order), 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 defines 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. Traversing a tree involves iterating (looping) over all nodes in some manner. Because from a given node there is more than one possible next node (it is not a linear data structure), then, assuming sequential computation (not parallel), some nodes must be deferred – stored in some way for later visiting. This is often done via a stack (FILO) or queue (FIFO). As a tree is a self-referential (recursively defined) data structure, traversal can naturally be described by recursion or, more subtly, corecursion, in which case the deferred nodes are stored implicitly – in the case of recursion, in the call stack. The name given to a particular style of traversal comes from the order in which nodes are visited. Most simply,

Recorrido del árbol

Embed Size (px)

Citation preview

Page 1: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

1/12en.wikipedia.org/wiki/Tree_traversal

Tree traversalFrom Wikipedia, the free encyclopedia

In computer science, tree traversal refers to the process of visiting (examining and/or updating) each node in atree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodesare visited. The following algorithms are described for a binary tree, but they may be generalized to other trees aswell.

Contents

1 Traversals

1.1 Depth-first traversal

1.2 Breadth-first traversal

2 Example

3 Infinite trees

4 Implementations4.1 Queue-based level order traversal

4.2 Uses

4.3 Functional traversal

4.4 Iterative Traversal

4.5 Recursive Traversals in C4.5.1 Inorder Traversal

4.5.2 Preorder Traversal

4.5.3 Postorder Traversal

5 References

6 External links

Traversals

Compared to linear data structures like linked lists and one dimensional arrays, which have a canonical method oftraversal (namely in linear order), tree structures can be traversed in many different ways. Starting at the root of abinary tree, there are three main steps that can be performed and the order in which they are performed defines thetraversal 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.

Traversing a tree involves iterating (looping) over all nodes in some manner. Because from a given node there ismore than one possible next node (it is not a linear data structure), then, assuming sequential computation (notparallel), some nodes must be deferred – stored in some way for later visiting. This is often done via a stack (FILO)or queue (FIFO). As a tree is a self-referential (recursively defined) data structure, traversal can naturally bedescribed by recursion or, more subtly, corecursion, in which case the deferred nodes are stored implicitly – in thecase of recursion, in the call stack.

The name given to a particular style of traversal comes from the order in which nodes are visited. Most simply,

Page 2: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

2/12en.wikipedia.org/wiki/Tree_traversal

does one go down first (depth-first: first child, then grandchild before second child) or across first (breadth-first:first child, then second child before grandchildren)? Depth-first traversal is further classified by position of the rootelement with regard to the left and right nodes. Imagine that the left and right nodes are constant in space, then theroot node could be placed to the left of the left node (pre-order), between the left and right node (in-order), or tothe right of the right node (post-order). There is no equivalent variation in breadth-first traversal – given ordering ofchildren, "breadth-first" is unambiguous.

For the purpose of illustration, it is assumed that left nodes always have priority over right nodes. This ordering canbe reversed as long as the same ordering is assumed for all traversal methods.

Depth-first traversal is easily implemented via a stack, including recursively (via the call stack), while breadth-firsttraversal is easily implemented via a queue, including corecursively.

Beyond these basic traversals, various more complex or hybrid schemes are possible, such as depth-limited searchssuch as iterative deepening depth-first search.

Depth-first traversal

See also: Depth-first search

Binary Tree

To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node,

starting with the root node[1]:

1. Visit the root.2. Traverse the left subtree.

3. Traverse the right subtree.

To traverse a non-empty binary tree in inorder (symmetric), perform the following operations recursively at each

node[1]:

1. Traverse the left subtree.

2. Visit the root.3. Traverse the right subtree.

To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node[1]:

1. Traverse the left subtree.

2. Traverse the right subtree.3. Visit the root.

Note that neither one sequentialisation according to pre-, in- or postorder describes the underlying tree uniquely;

any combination of two different sequentialisations enables full reconstruction, though[2].

Generic Tree

To traverse a non-empty tree in depth-first order, perform the following operations recursively at each node:

Page 3: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

3/12en.wikipedia.org/wiki/Tree_traversal

1. Perform pre-order operation

2. for i=1 to n-1 do1. Visit child[i], if present

2. Perform in-order operation3. Visit child[n], if present

4. Perform post-order operation

where n is the number of child nodes. Depending on the problem at hand, the pre-order, in-order or post-orderoperations may be void, or you may only want to visit a specific child node, so these operations should beconsidered optional. Also, in practice more than one of pre-order, in-order and post-order operations may berequired. For example, when inserting into a ternary tree, a pre-order operation is performed by comparing items.A post-order operation may be needed afterwards to rebalance the tree.

Breadth-first traversal

See also: Breadth-first search

Trees can also be traversed in level-order, where we visit every node on a level before going to a lower level.

Example

Binary tree:

Depth-first

Preorder traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)Inorder traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right); note how this produces a sorted

sequence

Postorder traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

Breadth-first

Page 4: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

4/12en.wikipedia.org/wiki/Tree_traversal

Level-order traversal sequence: F, B, G, A, D, I, C, E, H

pre-order in-order post-order level-order

push F

pop F

push B G

pop B

push A D I

pop A

pop D

push C E H

pop C

pop E

pop G

pop I

pop H

push F B A

pop A

pop B

push D C

pop C

pop D

push E

pop E

pop F

push G

pop G

push I H

pop H

pop I

push F B A

pop A

push D C

pop C

push E

pop E

pop D

pop B

push G I H

pop H

pop I

pop G

pop F

enqueue F

dequeue F

enqueue B G

dequeue B

enqueue A D

dequeue G

enqueue I

dequeue A

dequeue D

enqueue C E

dequeue I

enqueue H

dequeue C

dequeue E

dequeue H

Infinite trees

While tree traversal is generally done for finite trees – finite number of nodes, hence finite depth and finite branchingfactor – it can also be done for infinite trees. This is of particular interest in functional programming (particularly withlazy evaluation), as infinite data structures can often be easily defined and worked with, though they are not (strictly)evaluated, as this would take infinite time. More practically, some trees are, while finite, so large as to in practice beinfinite, such as the game tree for chess or go, and thus analyzing them as if they were infinite is useful – infinite treesare the limiting case of very large trees.

A basic requirement for traversal is to visit every node. For infinite trees, simple algorithms often fail this. Forexample, given a binary tree of infinite depth, a depth-first traversal will go down one side (by convention the leftside) of the tree, never visiting the rest, and indeed if in-order or post-order will never visit any nodes, as it has notreached a leaf (and in fact never will). By contrast, a breadth-first (level-order) traversal will traverse a binary treeof infinite depth without problem, and indeed will traverse any tree with bounded branching factor.

On the other hand, given a tree of depth 2, where the root node has infinitely many children, and each of thesechildren has two children, a depth-first traversal will visit all nodes, as once it exhausts the grandchildren (children ofchildren of one node), it will move on to the next (assuming it is not post-order, in which case it never reaches theroot). By contrast, a breadth-first traversal will never reach the grandchildren, as it seeks to exhaust the childrenfirst.

A more sophisticated analysis of running time can be given via infinite ordinal numbers; for example, the breadth-first traversal of the depth 2 tree above will take ω·2 steps: ω for the first level, and then another ω for the secondlevel.

Thus, simple depth-first or breadth-first searches do not traverse every infinite tree, and are not efficient on verylarge trees. However, hybrid methods can traverse any (countably) infinite tree, essentially via a diagonal argument(diagonal – combination of vertical and horizontal – corresponds to hybrid – combination of depth and breadth).

Concretely, given the infinitely branching tree of infinite depth, label the root node the children of the root node

Page 5: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

5/12en.wikipedia.org/wiki/Tree_traversal

the grandchildren and so forth. The nodes are thus in

a one-to-one correspondence with finite (possibly empty) sequences of positive numbers, which are countable andcan be placed in order first by sum of entries, and then by lexicographic order within a given sum (only finitely manysequences sum to a given value, so all entries are reached – formally there are a finite number of compositions of a

given natural number, specifically 2n−1 compositions of n ≥ 1;), which gives a traversal. Explicitly:

0: ()

1: (1)

2: (1,1) (2)

3: (1,1,1) (1,2) (2,1) (3)

4: (1,1,1,1) (1,1,2) (1,2,1) (1,3) (2,1,1) (2,2) (3,1) (4)

etc.

This can be alternatively interpreted as mapping the infinite depth binary tree onto this tree and then applyingbreadth-first traversal: replace the "down" edges connecting a parent node to its second and later children with"right" edges from the 1st child to the 2nd child, 2nd child to third child, etc. Thus at each step one can either godown (append a (,1) to the end) or go right (add 1 to the last number) (except the root, which is extra and can onlygo down), which shows the correspondence between the infinite binary tree and the above numbering; the sum of

the entries (minus 1) corresponds to the distance from the root, which agrees with the 2n−1 nodes at depth n−1 inthe infinite binary tree (2 corresponds to binary).

Implementations

preorder(node)

if node == null then return

print node.value

preorder(node.left)

preorder(node.right)

inorder(node)

if node == null then return

inorder(node.left)

print node.value

inorder(node.right)

postorder(node)

if node == null then return

postorder(node.left)

postorder(node.right)

print node.value

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

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

To traverse inorder (in-order) without recursion a tree, whose nodes contain parent pointers

Page 6: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

6/12en.wikipedia.org/wiki/Tree_traversal

typedef struct tNode{ struct tNode* child[2]; // NULLs for leaves struct tNode* parent; // NULL for root int data;} tNode; tNode * firstInOrderNode (tNode* root){ if (root == NULL) { // tree is empty return NULL; } // return leftmost node as first tNode *n = root; while (n->child[0] != NULL) { n = n->child[0]; } return n;} tNode * nextInOrderNode (tNode *n){ if (n->child[1] != NULL) { // we have a right subtree - next node is leftmost node in the right subtree n = n->child[1]; while (n->child[0] != NULL) { n = n->child[0]; } } else { // we do not have a right subtree - next node is the first node upwards that // does not contain this node in its right subtree (if there is no such node, // this is the last (rightmost) node, and we return NULL). while (n->parent != NULL && n == n->parent->child[1]) { n = n->parent; } n = n->parent; } return n;} void nonRecursiveInOrderTraversal (tNode* root){ for (tNode *n = firstInOrderNode(root); n != NULL; n = nextInOrderNode(n)) { printf("we are at %d\n", n->data); }}

The time complexity of a single iteration step using the above algorithm is limited by the height of the tree, which isO(log n) for balanced trees. However, since each edge is traversed exactly twice (once when entering a subtreeand once when leaving it), the amortized traversal time is O(n).

In the case of using threads, this will allow for greatly improved inorder traversal, although retrieving the parentnode 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

Page 7: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

7/12en.wikipedia.org/wiki/Tree_traversal

while node.parent ≠ null and node == node.parent.right do

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. Seethreaded binary trees for more information.

To traverse a threaded tree inorder (in-order) without recursion

void InOrderTraversal(struct Node *n){ struct Node *Cur, *Pre; if(n==NULL) return; Cur = n; while(Cur != NULL) { if(Cur->lptr == NULL) { printf("\t%d",Cur->val); Cur= Cur->rptr; } else { Pre = Cur->lptr; while(Pre->rptr !=NULL && Pre->rptr != Cur) Pre = Pre->rptr; if (Pre->rptr == NULL) { Pre->rptr = Cur; Cur = Cur->lptr; } else { Pre->rptr = NULL; printf("\t%d",Cur->val); Cur = Cur->rptr; } } }}

Queue-based level order traversal

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

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)

Page 8: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

8/12en.wikipedia.org/wiki/Tree_traversal

Uses

Inorder traversal

It is particularly common to use an inorder traversal on a binary search tree because this will return values from theunderlying 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 lessthan 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 subtreerooted at n in order. We can assume the recursive calls correctly visit the subtrees in order using the mathematicalprinciple of structural 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 copyof a binary search tree.

One can also use preorder traversals to get a prefix expression (Polish notation) from expression trees: traverse theexpression tree preorderly. To calculate the value of such an expression: scan from right to left, placing the elementsin a stack. Each time we find an operator, we replace the two top symbols of the stack with the result of applyingthe operator to those elements. For instance, the expression ∗ + 2 3 4, which in infix notation is (2 + 3) ∗ 4,would be evaluated like this:

Using prefix traversal to evaluatean expression tree

Expression (remaining) Stack

∗ + 2 3 4 <empty>

∗ + 2 3 4

∗ + 2 3 4

∗ + 2 3 4

∗ 5 4

Answer 20

Functional traversal

We could perform the same traversals in a functional language like Haskell using code similar to the below.Functional breadth-first traversal is one motivation for corecursion.

data Tree a = Nil | Node (Tree a) a (Tree a) preorder Nil = [] preorder (Node left x right) = [x] ++ (preorder left) ++ (preorder right)

Page 9: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

9/12en.wikipedia.org/wiki/Tree_traversal

postorder Nil = [] postorder (Node left x right) = (postorder left) ++ (postorder right) ++ [x] inorder Nil = [] inorder (Node left x right) = (inorder left) ++ [x] ++ (inorder right) levelorder t = step [t] where step [] = [] step ts = concatMap elements ts ++ step (concatMap subtrees ts) elements Nil = [] elements (Node left x right) = [x] subtrees Nil = [] subtrees (Node left x right) = [left, right]

Iterative Traversal

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

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

iterativePostorder(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 each node is required to keep an additional "visited" flag, other than usual information (value, left-child-reference, right-child-reference).

Another sample is shown here for postorder traversal without requiring any additional bookkeeping flags (C++):

void iterativePostOrder(Node* root) { if (!root) { return; } stack<Node*> nodeStack; Node* cur = root; while (true) { if (cur) { if (cur->right) { nodeStack.push(cur->right); } nodeStack.push(cur); cur = cur->left; continue; } if (nodeStack.empty()) { return; } cur = nodeStack.top();

Page 10: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

10/12en.wikipedia.org/wiki/Tree_traversal

nodeStack.pop(); if (cur->right && !nodeStack.empty() && cur->right == nodeStack.top()) { nodeStack.pop(); nodeStack.push(cur); cur = cur->right; } else { std::cout << cur->val << " "; cur = NULL; } }}

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

public void iterativePreorder(Node root) { Stack nodes = new Stack(); nodes.push(root); Node currentNode; while (!nodes.isEmpty()) { currentNode = nodes.pop(); Node right = currentNode.right(); if (right != null) { nodes.push(right); } Node left = currentNode.left(); if (left != null) { nodes.push(left); } System.out.println("Node data: "+currentNode.data); }}

If each node holds reference to the parent node, then iterative traversal is possible without a stack or "visited" flag.

Here is another example of iterative inorder traversal in (C++):

void iterativeInorder(Node* root) { stack<Node*> nodeStack; Node *curr = root; while (true) { if (curr) { nodeStack.push(curr); curr = curr->left; continue; } if (!nodeStack.size()) { return; } curr = nodeStack.top(); nodeStack.pop(); std::cout << "Node data: " << curr->data << std::endl; curr = curr->right; }}

Iterative inorder traversal in (Java):

public void traverseTreeInOrder(Node node) { //incoming node is root Stack<Node> nodes = new Stack<Node>(); while (!nodes.isEmpty() || null != node) { if (null != node) { nodes.push(node);

Page 11: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

11/12en.wikipedia.org/wiki/Tree_traversal

node = node.left; } else { node = nodes.pop(); System.out.println("Node value: " + node.value); node = node.right; } } }

Recursive Traversals in C

Recursive algorithms can be written for tree traversals. The data structure of the tree can be written as:[3]

typedef struct node { int val; struct node *left, *right;}*tree; //tree has been typedefed as a node pointer.

For the above data structure, the basic tree traversals can be written as shown below:

Inorder Traversal

void inorder(tree t) { if(t == NULL) return; inorder(t->left); printf("%d ", t->val); inorder(t->right);}

Preorder Traversal

void preorder(tree t) { if(t == NULL) return; printf("%d ", t->val); preorder(t->left); preorder(t->right);}

Postorder Traversal

void postorder(tree t) { if(t == NULL) return; postorder(t->left); postorder(t->right); printf("%d ", t->val);}

References

Page 12: Recorrido del árbol

08/08/12 Tree traversal - Wikipedia, the free encyclopedia

12/12en.wikipedia.org/wiki/Tree_traversal

1. ̂a b c http://webdocs.cs.ualberta.ca/~holte/T26/tree-traversal.html

2. ^ Which combinations of pre-, post- and in-order sequentialisation are unique?(http://cs.stackexchange.com/questions/439/which-combinations-of-pre-post-and-in-order-sequentialisation-are-unique)

3. ^ "Tree->Traversal" (http://datastructures.itgo.com/trees/traversal.htm) . Datastructures.itgo.com.http://datastructures.itgo.com/trees/traversal.htm. Retrieved 2012-02-24.

Dale, Nell. Lilly, Susan D. "Pascal Plus Data Structures". D. C. Heath and Company. Lexington, MA. 1995.

Fourth Edition.Drozdek, Adam. "Data Structures and Algorithms in C++". Brook/Cole. Pacific Grove, CA. 2001. Second

edition.http://www.math.northwestern.edu/~mlerma/courses/cs310-05s/notes/dm-treetran

External links

Animation Applet of Binary Tree Traversal

(http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/BTree.html)The Adjacency List Model for Processing Trees with SQL

(http://www.SQLSummit.com/AdjacencyList.htm)Storing Hierarchical Data in a Database (http://www.sitepoint.com/article/hierarchical-data-database) with

traversal examples in PHPManaging Hierarchical Data in MySQL (http://dev.mysql.com/tech-resources/articles/hierarchical-data.html)Working with Graphs in MySQL (http://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch20.html)

Non-recursive traversal of DOM trees in JavaScript(http://www.jslab.dk/articles/non.recursive.preorder.traversal)

Sample code for recursive and iterative tree traversal implemented in C.(http://code.google.com/p/treetraversal/)

Sample code for recursive tree traversal in C#.(http://arachnode.net/blogs/programming_challenges/archive/2009/09/25/recursive-tree-traversal-orders.aspx)

See tree traversal implemented in various programming language (http://rosettacode.org/wiki/Tree_traversal)on Rosetta Code

Tree traversal without recursion (http://www.perlmonks.org/?node_id=600456)

Retrieved from "http://en.wikipedia.org/w/index.php?title=Tree_traversal&oldid=506454666"

Categories: Trees (data structures) Articles with example Haskell code Articles with example Java code

Graph algorithms

This page was last modified on 8 August 2012 at 21:28.Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply.See Terms of use for details.

Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.