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--; } } } } }