剑指offer——第60题:把二叉树打印成多行(二叉树的层次遍历)

it2022-05-08  2

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

import java.util.ArrayList; import java.util.LinkedList; public class Solution { ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> lists = new ArrayList<>(); if (pRoot == null) { return lists; } LinkedList<TreeNode> queue = new LinkedList<>(); queue.add(pRoot); int level = 0; while (!queue.isEmpty()) { lists.add(new ArrayList<>()); int len = queue.size(); for (int i = 0; i < len; ++i) { TreeNode node = queue.pop(); lists.get(level).add(node.val); if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } } level++; } return lists; } }

二叉树的层次遍历:

import java.util.ArrayList; import java.util.LinkedList; public class T_60_LevelOrder { public ArrayList<Integer> leverOrder(TreeNode pRoot) { ArrayList<Integer> res = new ArrayList<>(); if (pRoot == null) { return res; } LinkedList<TreeNode> queue = new LinkedList<>(); queue.add(pRoot); TreeNode node; while (!queue.isEmpty()) { node = queue.poll(); res.add(node.val); if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } } return res; } }

最新回复(0)