劍指offer第二版-32.從上到下打印二叉樹

本系列導(dǎo)航:劍指offer(第二版)java實現(xiàn)導(dǎo)航帖

面試題32:從上到下打印二叉樹

題目要求:
從上到下打印二叉樹的每個節(jié)點,同一層的節(jié)點按照從左到右的順序打印。

解題思路:
這道題就是二叉樹的層序遍歷。使用一個隊列,進(jìn)行廣度優(yōu)先遍歷即可。

package structure;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Created by ryder on 2017/6/12.
 * 樹節(jié)點
 */
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);
    }
}

運行結(jié)果

1   2   3   4   5   6   7   
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容