剑指Offer:面试题23——从上往下打印二叉树(java实现)

问题描述:

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

思路:

按照层次遍历的方法,使用队列辅助。
1.将根结点加入队列。
2.循环出队,打印当前元素,若该结点有左子树,则将其加入队列,若有右子树,将其加入队列。
3.直到队列为空,表明已经打印完所有结点。

代码:

import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;

public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null){
            return result;
        }

        Queue<TreeNode> q = new LinkedList<TreeNode>();

        q.add(root);        
        while(!q.isEmpty()){
            TreeNode tmp = q.remove();
            result.add(tmp.val);
            if(tmp.left != null){
                q.add(tmp.left);
            }

            if(tmp.right != null){
                q.add(tmp.right);

            }

        }

        return result;
    }
}
原文地址:https://www.cnblogs.com/wenbaoli/p/5655711.html