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

【数据结构】二叉树层次遍历

时间:2015-04-13 09:40:58      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:二叉树-层次遍历   数据结构   

package 蓝桥练习;

public class 二叉树层次遍历 {

    public static int MAXSIZE = 100;

    public static Node queue[] = new Node[MAXSIZE];

    public static void main(String[] args) {
        Node h = new Node(‘H‘, null, null);
        Node i = new Node(‘I‘, null, null);
        Node f = new Node(‘F‘, h, i);
        Node g = new Node(‘G‘, null, null);
        Node d = new Node(‘D‘, null, null);
        Node e = new Node(‘E‘, null, null);
        Node b = new Node(‘B‘, d, e);
        Node c = new Node(‘C‘, f, g);
        Node a = new Node(‘A‘, b, c);
        level(a);
    }

    /**
     * 层次遍历二叉树
     * @param p
     */
    private static void level(Node p) {
        int front, rear;
        front = rear = 0;
        Node q;
        if (p != null) {
            rear = (rear + 1) % MAXSIZE;
            queue[rear] = p;
            while (front != rear) {
                front = (front + 1) % MAXSIZE;
                q = queue[front];
                System.out.print(q.key + " ");
                if (q.leftNode != null) {
                    rear = (rear + 1) % MAXSIZE;
                    queue[rear] = q.leftNode;
                }
                if (q.rightNode != null) {
                    rear = (rear + 1) % MAXSIZE;
                    queue[rear] = q.rightNode;
                }
            }
        }
    }

}

class Node {
    public char key;
    public Node leftNode;
    public Node rightNode;

    public Node(char key) {
        this(key, null, null);
    }

    public Node(char key, Node leftNode, Node rightNode) {
        this.key = key;
        this.leftNode = leftNode;
        this.rightNode = rightNode;
    }
}

【数据结构】二叉树层次遍历

标签:二叉树-层次遍历   数据结构   

原文地址:http://blog.csdn.net/tracysilocean/article/details/45014205

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