二叉树的层序遍历

二叉树的层序遍历:

这道题目的解决方案就是,根结点入队列,随后循环执行结点出队列并打印结果,左孩子入队列,右孩子入队列。直到队列为空。如下图所示:

 

2.gif

 

public static void levelTraverse(Node root) {
    LinkedList<Node> queue = new LinkedList<Node>();
    Node current = null;
    queue.offer(root); // 根结点入队    
    while (!queue.isEmpty()) {
        current = queue.poll(); // 出队队头元素
        System.out.print(current.data);
        // 左子树不为空,入队
        if (current.leftChild != null)
            queue.offer(current.leftChild);
        // 右子树不为空,入队
        if (current.rightChild != null)
            queue.offer(current.rightChild);
    }
}

 

posted @ 2020-07-18 17:21  gaopengpy  阅读(156)  评论(0)    收藏  举报