"Tree" Binary Tree traversal algorithm (depth-first, breadth-first traversal, pre-order, middle order, sequence, hierarchy) and Java implementation

Source: Internet
Author: User

Binary tree is a very important data structure, and many other data structures are based on the evolution of binary tree basis. For binary tree, there are depth traversal and breadth traversal, depth traversal has pre-order, middle order and three kinds of traversal methods, and breadth traversal is what we usually call hierarchical traversal. Since the definition of a tree is itself a recursive definition, the recursive approach to implementing the three traversal of the tree is not only easy to understand, but the code is concise, and for breadth traversal, other data structures such as heap are needed. Therefore, for a piece of code, readability is sometimes more important than the efficiency of the code itself.

The four main traversal ideas are:

Pre-sequence Traversal: root node---> Left dial hand tree---> right subtree

Middle sequence traversal: Left dial hand tree---> root node---> right subtree

Post-order traversal: Left dial hand tree---> right subtree---> root node

Hierarchical traversal: simply traverse by hierarchy

For example, a variety of traversal of the following two-fork tree is asked

Pre-sequence Traversal: 1 2 4 5 7 8 3 6

Middle Sequence Traversal: 4 2 7 5 8 1 3 6

Post-Post traversal: 4 7 8 5 2 6 3 1

Hierarchical traversal: 1 2 3 4 5 6 7 8

First, pre-sequence traversal

1) According to the traversal idea mentioned above: root node ---> Left dial hand tree---> right subtree, very easy to write a recursive version:

 Public void preOrderTraverse1 (TreeNode root) {          ifnull) {              System.out.print (root.val +"  ");              PreOrderTraverse1 (root.left);              PreOrderTraverse1 (root.right);          }  }  

2) Now discuss the non-recursive version:

Based on the order of the pre-order traversal, the root node is accessed first, and then the Saozi right subtree is accessed. Therefore, for any node node, the first part is the direct access, and then in determining whether Zuozi is empty, not empty, then repeat the above steps until it is empty. If it is empty, you need access to the right subtree. Note that after you have accessed the left child, you need to access its right child in turn, so you need support for this data structure on the stack. For any node node, the steps are as follows:

A) access, and the node node into the stack, the current node is left child;

b) Determine whether node node is empty, if it is empty, then take out the top node of the stack and out of the stack, the right child as the current node, or repeat a) step until the current node is empty or the stack is empty (you can find the node in the stack is to access the right child to store)

The code is as follows:

1  Public voidpreOrderTraverse2 (TreeNode root) {2linkedlist<treenode> stack =NewLinkedlist<>(); 3TreeNode Pnode =Root; 4          while(Pnode! =NULL|| !Stack.isempty ()) {  5             if(Pnode! =NULL) {  6System.out.print (pnode.val+ ""); 7 Stack.push (Pnode); 8Pnode =Pnode.left; 9}Else{//Pnode = = null &&!stack.isempty ()TenTreeNode node =Stack.pop ();  OnePnode =Node.right;  A             }   -         }   -}

Second, middle sequence traversal

1) According to the traversal idea mentioned above: Left Dial hand tree---> root node---> right subtree, it is easy to write a recursive version:

1  Public void inOrderTraverse1 (TreeNode root) {  2         ifnull) {  3              inOrderTraverse1 (root.left);   4             System.out.print (root.val+ "  ");   5             inOrderTraverse1 (root.right);   6         }  7     }  


2) Non-recursive implementation, with the interpretation of the previous order, the middle sequence is relatively simple, the same truth. Only the order of the accesses is moved to the out stack. The code is as follows:

1  Public voidinOrderTraverse2 (TreeNode root) {2linkedlist<treenode> stack =NewLinkedlist<>(); 3TreeNode Pnode =Root; 4          while(Pnode! =NULL|| !Stack.isempty ()) {  5             if(Pnode! =NULL) {  6 Stack.push (Pnode); 7Pnode =Pnode.left; 8}Else{//Pnode = = null &&!stack.isempty ()9TreeNode node =Stack.pop (); TenSystem.out.print (node.val+ "");  OnePnode =Node.right;  A             }   -         }   -}

Third, post-sequential traversal

1) According to the traversal idea mentioned above: Left Dial hand tree---> right subtree---> root node, it is easy to write a recursive version:

 Public void postOrderTraverse1 (TreeNode root) {          ifnull) {              postOrderTraverse1 (root.left );              PostOrderTraverse1 (root.right);              System.out.print (root.val+ "  ");          }      }  

2) non-recursive code, do not write

Four, hierarchical traversal

Hierarchical traversal of the code is relatively simple, only need a queue, first in the queue to join the root node. Then, for any node, it is accessed when it is out of the queue. At the same time if the left child and right child have not been empty, the queue is listed. The code is as follows:

1  Public voidleveltraverse (TreeNode root) {2         if(Root = =NULL) {  3             return; 4         }  5linkedlist<treenode> queue =NewLinkedlist<>(); 6 Queue.offer (root); 7          while(!Queue.isempty ()) {  8TreeNode node =Queue.poll (); 9System.out.print (node.val+ ""); Ten             if(Node.left! =NULL) {   One Queue.offer (Node.left);  A             }   -             if(Node.right! =NULL) {   - Queue.offer (node.right);  the             }   -         }   -}

V. Depth-First traversal

In fact, depth traversal is the upper order, the middle sequence and the order. But in order to ensure that the breadth-first traversal, also written in this. The code is also better understood, in fact, is the pre-sequence traversal, the code is as follows:

1  Public voiddepthordertraverse (TreeNode root) {2         if(Root = =NULL) {  3             return; 4         }  5linkedlist<treenode> stack =NewLinkedlist<>(); 6 Stack.push (root); 7          while(!Stack.isempty ()) {  8TreeNode node =Stack.pop (); 9System.out.print (node.val+ ""); Ten             if(Node.right! =NULL) {   One Stack.push (node.right);  A             }   -             if(Node.left! =NULL) {   - Stack.push (Node.left);  the             }   -         }   -}

Source:

http://blog.csdn.net/my_jobs/article/details/43451187

Tree binary Tree Traversal algorithm (depth-first, breadth-first traversal, pre-order, middle order, sequence, hierarchy) and Java implementation

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.