题解 | #牛群分层排列#
牛群分层排列
https://www.nowcoder.com/practice/7e98027a60424c9ba88d9c4c0506ede4
题目考察的知识点是:
二叉树的层序遍历。
题目解答方法的文字分析:
二叉树的层序遍历常借助于队列来实现,队列的特性为先进先出。我们将二叉树的结点加入队列尾部,弹出结点从队列头部,使得二叉树正确的进行层序遍历,java队列的实现常用LinkedList,java没有队列的封装只能使用LinkedList来作为队列的实现。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return string字符串一维数组 */ public String[] levelOrder (TreeNode root) { // write code here List<String> list = new ArrayList(); Queue<TreeNode> queue = new LinkedList(); if (root == null) return new String[]{}; queue.add(root); while(!queue.isEmpty()){ String index = ""; for(TreeNode p : queue){ index += p.val; } list.add(index); int size = queue.size(); while(size-- > 0){ TreeNode node = queue.poll(); if (node.left != null){ queue.add(node.left); } if (node.right != null){ queue.add(node.right); } } } return list.toArray(new String[list.size()]); } }#题解#