剑指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<T> {
    public T val;
    public TreeNode<T> left;
    public TreeNode<T> 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<Integer> root){
        if(root==null)
            return;
        Queue<TreeNode<Integer>> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode<Integer> 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<Integer> root = new TreeNode<Integer>(1);
        root.left = new TreeNode<Integer>(2);
        root.right = new TreeNode<Integer>(3);
        root.left.left = new TreeNode<Integer>(4);
        root.left.right = new TreeNode<Integer>(5);
        root.right.left = new TreeNode<Integer>(6);
        root.right.right = new TreeNode<Integer>(7);
        printFromTopToBottom(root);
    }
}

运行结果

1   2   3   4   5   6   7   
    原文作者:ryderchan
    原文地址: https://www.jianshu.com/p/1b8a0cc54d57#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞