Depth and breadth Traversal

Source: Internet
Author: User

Depth first search is a search algorithm. It is the node that traverses the tree along the tree in depth, and the branch of the search tree is as deep as possible.

When all the edges of node v have been explored, the search will trace back to the Start Node of the edge of node v. This process continues until all nodes that can be reached from the source node are found.

If no node is found, select one of the nodes as the source node and repeat the above process until all nodes are accessed.


The binary tree shown in the right figure is:

A is the first access, followed by B and D, followed by E. Then C, F, and G.

So how can we ensure the access order?

After traversing the root node, we start to traverse the left subtree, and finally the right subtree.

Therefore, we can use the data structure of the stack. Because the stack is in the first-in-first-out order, we can first press the right subtree to stack, and then press the stack on the left subtree,

In this way, the left subtree node has a stack top, so the left subtree of a node can be traversed before its right subtree traversal.

Depth-first traversal of code snippets


// Depth-first Traversal
Void depthfirstsearch (tree root ){
Stack <node *> nodestack; // use the C ++ STL standard template library
Nodestack. Push (Root );
Node * node;
While (! Nodestack. Empty ()){
Node = nodestack. Top ();
Printf (format, node-> data); // traverse the root node
Nodestack. Pop ();
If (node-> rchild ){
Nodestack. Push (node-> rchild); // first press the right subtree to stack
}
If (node-> lchild ){
Nodestack. Push (node-> lchild); // press the left subtree onto the stack.
}
}
}


Breadth First search, also known as width-first or horizontal-first search.

The node that traverses the tree from the root node along the width of the tree. If all nodes are accessed, the algorithm is aborted.

In the binary tree shown in the right figure, a is the first access, followed by B and C, followed by D, E, F, and G.

So how can we ensure the access order?

With the help of the queue data structure, because the queue is in the first-in-first-out order, you can first join the left subtree and then the right subtree.

In this way, the left subtree node has a queue header, which can be accessed first.

Traversing code snippets with breadth first


// Traverse the breadth first
Void breadthfirstsearch (tree root ){
Queue <node *> nodequeue; // use the C ++ STL standard template library
Nodequeue. Push (Root );
Node * node;
While (! Nodequeue. Empty ()){
Node = nodequeue. Front ();
Nodequeue. Pop ();
Printf (format, node-> data );
If (node-> lchild ){
Nodequeue. Push (node-> lchild); // queues the left subtree first.
}
If (node-> rchild ){
Nodequeue. Push (node-> rchild); // enter the right subtree
}
}
}


Complete code:


/**
* <! --
* File: binarytree. h
* Author: fancy
* Email: [email protected]
* Date: 2013-02-03
* --!>
*/
# Include <stdio. h>
# Include <stdlib. h>
# Include <malloc. h>
# Include <stack>
# Include <queue>
Using namespace STD;
# Define element char
# Define format "% C"

Typedef struct node {
Element data;
Struct node * lchild;
Struct node * rchild;
} * Tree;

Int Index = 0; // global index variable

// Binary Tree constructor, which constructs a binary tree in the order of first Traversal
// Use '#' to represent the left subtree or the right subtree
Void treenodeconstructor (Tree & root, element data []) {
Element E = data [index ++];
If (E = '#'){
Root = NULL;
} Else {
Root = (node *) malloc (sizeof (node ));
Root-> DATA = E;
Treenodeconstructor (root-> lchild, data); // recursively construct the left subtree
Treenodeconstructor (root-> rchild, data); // recursively construct the right subtree
}
}

// Depth-first Traversal
Void depthfirstsearch (tree root ){
Stack <node *> nodestack; // use the C ++ STL standard template library
Nodestack. Push (Root );
Node * node;
While (! Nodestack. Empty ()){
Node = nodestack. Top ();
Printf (format, node-> data); // traverse the root node
Nodestack. Pop ();
If (node-> rchild ){
Nodestack. Push (node-> rchild); // first press the right subtree to stack
}
If (node-> lchild ){
Nodestack. Push (node-> lchild); // press the left subtree onto the stack.
}
}
}

// Traverse the breadth first
Void breadthfirstsearch (tree root ){
Queue <node *> nodequeue; // use the C ++ STL standard template library
Nodequeue. Push (Root );
Node * node;
While (! Nodequeue. Empty ()){
Node = nodequeue. Front ();
Nodequeue. Pop ();
Printf (format, node-> data );
If (node-> lchild ){
Nodequeue. Push (node-> lchild); // queues the left subtree first.
}
If (node-> rchild ){
Nodequeue. Push (node-> rchild); // enter the right subtree
}
}
}

 

Binary Tree depth-first traversal (in-order traversal ):

When we use the depth-first traversal of the tree to find a path that meets the conditions, we need to set a bool type flag. If it is already found in the left subtree, the right subtree does not need to be recursive, follow these steps:

Bool findpath (pcur, pnode)

If (meets the conditions)

Return true;

S. Push (pcur );

Bool found = false; // set a flag to determine whether a path has been found.

If (pcur-> left)

Found = findpath (pcur-> left, pnode );

If (pcur-> Right &&! Found) // if it is found, no recursion is required.

Found = findpath (pcur-> right, pnode );

If (! Found)

S. Pop ();

Return found;

When we need to find all the paths that meet the conditions, we generally take the following steps:

Void findpath (pcur, pnode)

If (meets the conditions)

Print;

Update status;

S. Push (pcur );

If (pcur-> left)

Findpath (pcur-> left, pnode );

If (pcur-> right)

Findpath (pcur-> right, pnode );

Restores the status when this node is added;

S. Pop ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.