题解 | #牛群的二叉树排序#

牛群的二叉树排序

https://www.nowcoder.com/practice/a3a8756cbb13493ab4cf5d73c853d5cd

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 cows int整型一维数组 
     * @return TreeNode类
     */
    public TreeNode sortCowsTree (int[] cows) {
        // write code here
        int c1 = 0;
        int c2 = 0;
        for (int n : cows) {
            if (n == 0) c1++;
            else c2++;
        }
        TreeNode root = new TreeNode(-1);
        if (c1 > 0) root.left = new TreeNode(0);
        if (c2 > 0) root.right = new TreeNode(1);
        c1--;
        c2--;
        m(c1, 0, root.left);
        m(c2, 1, root.right);
        return root;
    }
    //层序遍历的思想
    public void m(int c, int n, TreeNode root) {
        if (root == null) return;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node != null) {
                if (c > 0) {
                    TreeNode n1 = new TreeNode(n);
                    node.left = n1;
                    q.add(n1);
                    c--;
                }
                if (c > 0) {
                    TreeNode n1 = new TreeNode(n);
                    node.right = n1;
                    q.add(n1);
                    c--;
                }
            }
        }

    }

}

全部评论

相关推荐

06-25 16:53
门头沟学院 Java
人力小鱼姐:简历可以直接用飞书模板 模拟面试可以试试ai,现在好多都还是免费阶段 像Sugar云面、多面鹅都不错,主要看面试后自己能不能复盘出有效信息
为了找工作你花了哪些钱?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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