二叉树前中后递归遍历

1 public class Node {
2     public int value;
3     public Node left;
4     public Node right;
5 
6     public Node (int data){
7         this.value = data;
8     }
9 }
 1 public class BinaryTreeMethod {
 2 
 3     /**
 4      * 二叉树递归前序遍历
 5      * @param head
 6      */
 7     public void preOrderRecur(Node head){
 8         if(head == null){
 9             return;
10         }
11         System.out.print(head.value + " ");
12         preOrderRecur(head.left);
13         preOrderRecur(head.right);
14     }
15 
16     /**
17      * 二叉树递归中序遍历
18      * @param head
19      */
20     public void inOrderRecur(Node head){
21         if(head == null){
22             return;
23         }
24         inOrderRecur(head.left);
25         System.out.print(head.value + " ");
26         inOrderRecur(head.right);
27     }
28 
29     /**
30      * 二叉树递归后序遍历
31      * @param head
32      */
33     public void postOrderRecur(Node head){
34         if(head == null){
35             return;
36         }
37         postOrderRecur(head.left);
38         postOrderRecur(head.right);
39         System.out.print(head.value + " ");
40     }
41 }

测试代码:

 1 public class Test {
 2 
 3     public  static void  main(String[] args){
 4         Node head = new Node(3);
 5         Node left = new Node(5);
 6         Node right = new Node(2);
 7         head.left = left;
 8         head.right = right;
 9 
10         left.left = new Node(1);
11         right.left = new Node(7);
12 
13         BinaryTreeMethod method = new BinaryTreeMethod();
14         method.preOrderRecur(head);
15         System.out.println();
16         method.inOrderRecur(head);
17         System.out.println();
18         method.postOrderRecur(head);
19     }
20 }
原文地址:https://www.cnblogs.com/huangyichun/p/6010276.html