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

package tree;

import common.Print;
import common.TreeNode;

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

public class 从上往下打印二叉树 {
    /**
     * 先进先出,用队列实现。弹一个出来,把左边右边加进去
     * bfs的思想
     */
    public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        if (root == null) {
            return arrayList;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode cur;
        while (!queue.isEmpty()) {
            cur = queue.poll();
            arrayList.add(cur.val);
            // 先进先出,左边先出,左边也要先进
            if (cur.left != null) {
                queue.add(cur.left);
            }
            if (cur.right != null) {
                queue.add(cur.right);
            }
        }
        return arrayList;
    }
}

results matching ""

    No results matching ""