2022-7-1 剑指offer-树-层序遍历
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int[] levelOrder(TreeNode root) { 12 if (root==null) return new int[]{}; 13 Queue<TreeNode> queue=new LinkedList<>(); 14 queue.offer(root); 15 List<Integer> list=new ArrayList<>(); 16 while (!queue.isEmpty()){ 17 int len=queue.size(); 18 for (int i=0;i<len;i++){ 19 TreeNode temp=queue.poll(); 20 list.add(temp.val); 21 if (temp.left!=null) queue.offer(temp.left); 22 if (temp.right!=null) queue.offer(temp.right); 23 } 24 } 25 int[] ans=new int[list.size()]; 26 for (int i=0;i<list.size();i++){ 27 ans[i]=list.get(i); 28 } 29 return ans; 30 } 31 }
思路:队列实现层序遍历。