剑指offer第二版-32.从上到下打印二叉树

本系列导航:剑指offer(第二版)java实现导航帖

面试题32:从上到下打印二叉树

题目要求:
从上到下打印二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

解题思路:
这道题就是二叉树的层序遍历。使用一个队列,进行广度优先遍历即可。

package structure;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Created by ryder on 2017/6/12.
 * 树节点
 */
public class TreeNode {
    public T val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(T val){
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
package chapter4;
import structure.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Created by ryder on 2017/7/17.
 * 从上到下打印二叉树(层序遍历)
 */
public class P171_PrintTreeFromTopToBottom {
    public static void printFromTopToBottom(TreeNode root){
        if(root==null)
            return;
        Queue> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode temp;
        while(!queue.isEmpty()){
            temp = queue.poll();
            System.out.print(temp.val);
            System.out.print('\t');
            if(temp.left!=null)
                queue.offer(temp.left);
            if(temp.right!=null)
                queue.offer(temp.right);
        }
    }
    public static void main(String[] args){
        //            1
        //          /   \
        //         2     3
        //       /  \   / \
        //      4    5 6   7
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        printFromTopToBottom(root);
    }
}

运行结果

1   2   3   4   5   6   7   

你可能感兴趣的:(剑指offer第二版-32.从上到下打印二叉树)