Binary tree data structure of articles Volume II - recursive binary tree traversal (With Java)

A first order recursive traversal (Preorder Recursive Traversal)

1.1 algorithm

  First, be clear in terms of order here is for the root node. I.e., so the first order first "visit" the root node, followed by "visit" the left and right nodes.

1.2 illustrates

1.3 Code

  Talk is cheap, show me the code!    -- Linus Benedict Torvalds

1     public void preOrder(Node<E> root){
2         if(root != null) {
3             System.out.print(root.data);
4             System.out.print('\t');
5             preOrder(root.lnode);
6             preOrder(root.rnode);
7         }
8     }

 

 

Second, in order recursive traversal (Inorder Recursive Traversal)

2.1 algorithm

  root from the root node, the first "visit" the left subtree (Left Subtree), when each node in the left subtree are "visiting" After only access the root node, the last "visit" the right subtree (Right Subtree).

2.2 icon

2.3 Code

 1  public void inOrder(Node<E> root){
 2         if(root != null) {
 3             //track to the deepest left branch
 4             inOrder(root.lnode);
 5             //visit the root node
 6             System.out.print(root.data);
 7             System.out.print('\t');
 8             inOrder(root.rnode);
 9         }
10     }

 

 

三、后序递归遍历(Postorder Recursive Traversal)

3.1 算法

  根节点是最后“访问”的,不管是在根节点所在的整棵树,还是根节点以下的子树都是先“访问”左子树中的节点,其次是右子树中节点,最后“访问”根节点。

3.2 图示

3.3 代码

 1     public void postOrder(Node<E> root){
 2         if(root != null) {
 3             //track to the deepest left branch
 4             postOrder(root.lnode);
 5             //track to the deepest right branch
 6             postOrder(root.rnode);
 7             //after visiting all the nodes of both left subtree and right subtree
 8             System.out.print(root.data);
 9             System.out.print('\t');
10         }
11     }

注意:层次遍历不能递归,可以结合递归条件想想为什么哦 :)

keep reading ,keep learning, keep coding…

 

Guess you like

Origin www.cnblogs.com/sheepcore/p/11580677.html