码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树遍历

时间:2015-04-13 22:40:17      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

先序遍历

先序遍历是先访问根结点,再左子树,再右子树。

中序遍历

中序遍历是先访问左子树,再根结点,再右子树。

后序遍历

后序遍历是先访问左子树,再右子树,再根结点。

 

 1 package cn.lihao;
 2 
 3 public class Node {
 4 
 5     private int data;
 6 
 7     private Node left;
 8     private Node right;
 9 
10     public Node(int data) {
11         this.data = data;
12     }
13 
14     public void add(int data) {
15         // 左边
16         if (this.data > data) {
17             if (this.left == null) {
18                 Node node = new Node(data);
19                 this.left = node;
20 
21             } else {
22                 this.left.add(data);
23             }
24         } else{
25             if (this.right == null) {
26                 Node node = new Node(data);
27                 this.right = node;
28             } else {
29                 this.right.add(data);
30             }
31         }
32     }
33 
34     
35     public void proPrint() {
36         //先序
37         //System.out.println(this.data);
38         if (this.left != null) {
39             this.left.proPrint();
40         }
41         // 中序
42         System.out.println(this.data);        
43         if (this.right != null) {
44             this.right.proPrint();
45         }
46         // 后序
47         //System.out.println(this.data);    
48     }
49 }

 

主方法

public class Tree01 {
    
    private  Node node;
    
    public  void add(int data){
        if(node == null) {
            node = new Node(data);
        } else {
            node.add(data);
        }
        
    }
    public void proprint(){
        node.proPrint();
    }

    public static void main(String[] args) {
        
        Tree01 tree = new Tree01();
        tree.add(5);
        tree.add(7);
        tree.add(3);
        tree.add(2);
        tree.add(1);
        tree.add(6);
        tree.add(4);
        tree.add(8);
        tree.add(10);
        tree.proprint();
        
    }
}

 

二叉树遍历

标签:

原文地址:http://www.cnblogs.com/lihaolihao/p/4423170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!