题解 | #牛群分层排列#

牛群分层排列

https://www.nowcoder.com/practice/7e98027a60424c9ba88d9c4c0506ede4

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
        ArrayList<String> list = new  ArrayList<String>();
        if (root == null) {
            return new String[0];
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            String str = "";
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                str += node.val;
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            list.add(str);
        }
        String strs[] = new String[list.size()];
        for (int i = 0; i < strs.length; i++) {
            strs[i] = list.get(i);
        }
        return strs;
    }
}

全部评论

相关推荐

程序员花海_:抓紧时间去找实习 项目其实只是玩具项目 脱离业务很远的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务