标签:def span queue root ret arraylist turn == remove
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if(root == null){ return res; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); int level = 0; while(!queue.isEmpty()){ res.add(new ArrayList<>()); int levelLength = queue.size(); for(int i = 0; i < levelLength; i++){ TreeNode node = queue.remove(); res.get(level).add(node.val); if(node.left != null){ queue.add(node.left); } if(node.right != null){ queue.add(node.right); } } level++; } return res; } } /* 二叉树或者多叉树的层次遍历要用队列,将当前子树保存下来,从队列中去除每个节点然后逐层遍历 */
标签:def span queue root ret arraylist turn == remove
原文地址:https://www.cnblogs.com/zhaijiayu/p/11594950.html