Skip to content

Latest commit

 

History

History
24 lines (21 loc) · 965 Bytes

JZ22_从上往下打印二叉树.md

File metadata and controls

24 lines (21 loc) · 965 Bytes

JZ22_从上往下打印二叉树

层序遍历二叉树,题目并没有在建树的问题上为难我,那么可以用现成的有先进先出的集合框架来做,也可以用手写链队,如果题目给出树中的元素的个数的上限,也可以自己写个数组用循环队列,这里偷懒了,用了线程的链表

public class Solution {
    LinkedList<TreeNode> linkedList;
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        linkedList = new LinkedList<>();
        ArrayList<Integer> ans = new ArrayList<>();
        if (root == null) return ans;
        linkedList.add(root);
        while (linkedList.size() > 0) {
            TreeNode temp = linkedList.getFirst();
            linkedList.removeFirst();
            ans.add(temp.val);
            if (temp.left != null) linkedList.add(temp.left);
            if (temp.right != null) linkedList.add(temp.right);
        }
        return ans;
    }
}