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

牛群的二叉树排序

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 zeros = 0, ones = 0;
        for (int i : cows) {
            if (i == 0) zeros++;
            else ones++;
        }
        TreeNode root = new TreeNode(-1);
        if (zeros > 0) {
            TreeNode zero = new TreeNode(0);
            root.left = zero;
            makeTree(zero, zeros - 1, 0);
        }
        if (ones > 0) {
            TreeNode one = new TreeNode(1);
            root.right = one;
            makeTree(one, ones - 1, 1);
        }
        return root;
    }

    private void makeTree(TreeNode root, int num, int flag) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (num > 0) {
            TreeNode temp = queue.poll();
            TreeNode lTemp = new TreeNode(flag);
            temp.left = lTemp;
            queue.offer(lTemp);
            num--;
            if (num > 0) {
                TreeNode rTemp = new TreeNode(flag);
                temp.right = rTemp;
                queue.offer(rTemp);
                num--;
            }
        }
    }
}

全部评论

相关推荐

找不到工作死了算了:没事的,雨英,hr肯主动告知结果已经超越大部分hr了
点赞 评论 收藏
分享
无情咸鱼王的秋招日记之薛定谔的Offer:好拒信,偷了,希望有机会用到
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务