剑指Offer--从上到下打印二叉树

题目描述

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

题解

遍历规则为从上到下,同层节点从左到右。采用队列的特性,先将二叉树的根节点放入队列中,然后根节点出队列,假设根节点有左孩子,则将左孩子加入队列中,根节点有右孩子,则将右孩子加入队列中,然后将根节点的值存入ArrayList,依次类推,即为答案。

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
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> arrayList = new ArrayList<>();
		Queue<TreeNode> queue = new LinkedList<>();
		if (root != null) {
			queue.add(root);
			while (!queue.isEmpty()) {
				TreeNode next = queue.poll();
				arrayList.add(next.val);
				if (next.left != null)
					queue.add(next.left);
				if (next.right != null)
					queue.add(next.right);
			}
		}
		return arrayList;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39290830/article/details/84786818