给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]
输入:{1,2}
输出:[[1],[2]]
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) { // write code here ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (root == null ){ return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()){ ArrayList<Integer> floor = new ArrayList<Integer>(); int len = queue.size(); for (int i=0; i<len;i++){ TreeNode temp = queue.poll(); floor.add(temp.val); if (temp.left !=null){ queue.offer(temp.left); } if (temp.right !=null){ queue.offer(temp.right); } } result.add(floor); } return result; } }
原文:https://www.cnblogs.com/jieran/p/14584303.html