|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +/** |
| 9 | + * 1361. Validate Binary Tree Nodes |
| 10 | + * |
| 11 | + * You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], |
| 12 | + * return true if and only if all the given nodes form exactly one valid binary tree. |
| 13 | + * If node i has no left child then leftChild[i] will equal -1, similarly for the right child. |
| 14 | + * Note that the nodes have no values and that we only use the node numbers in this problem. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] |
| 18 | + * Output: true |
| 19 | + * |
| 20 | + * Example 2: |
| 21 | + * Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] |
| 22 | + * Output: false |
| 23 | + * |
| 24 | + * Example 3: |
| 25 | + * Input: n = 2, leftChild = [1,0], rightChild = [-1,-1] |
| 26 | + * Output: false |
| 27 | + * |
| 28 | + * Example 4: |
| 29 | + * Input: n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1] |
| 30 | + * Output: false |
| 31 | + * |
| 32 | + * Constraints: |
| 33 | + * 1 <= n <= 10^4 |
| 34 | + * leftChild.length == rightChild.length == n |
| 35 | + * -1 <= leftChild[i], rightChild[i] <= n - 1 |
| 36 | + * */ |
| 37 | +public class _1361 { |
| 38 | + public static class Solution1 { |
| 39 | + public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) { |
| 40 | + int[] indegree = new int[n]; |
| 41 | + for (int i = 0; i < n; i++) { |
| 42 | + if (leftChild[i] >= 0) { |
| 43 | + indegree[leftChild[i]]++; |
| 44 | + } |
| 45 | + if (rightChild[i] >= 0) { |
| 46 | + indegree[rightChild[i]]++; |
| 47 | + } |
| 48 | + } |
| 49 | + //only one node has in-degree = 0 |
| 50 | + int indegreeZero = 0; |
| 51 | + for (int num : indegree) { |
| 52 | + if (num == 0) { |
| 53 | + indegreeZero++; |
| 54 | + if (indegreeZero > 1) { |
| 55 | + return false; |
| 56 | + } |
| 57 | + } |
| 58 | + //every other node's in-degree must be exactly equal to 1 |
| 59 | + if (num > 1) { |
| 60 | + return false; |
| 61 | + } |
| 62 | + } |
| 63 | + //no bi-directional pointing |
| 64 | + Map<Integer, List<Integer>> map = new HashMap<>(); |
| 65 | + for (int i = 0; i < n; i++) { |
| 66 | + map.put(i, new ArrayList<>()); |
| 67 | + map.get(i).add(leftChild[i]); |
| 68 | + map.get(i).add(rightChild[i]); |
| 69 | + } |
| 70 | + for (int node : map.keySet()) { |
| 71 | + List<Integer> children = map.get(node); |
| 72 | + for (int child : children) { |
| 73 | + if (map.containsKey(child) && map.get(child).contains(node)) { |
| 74 | + return false; |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + return true; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments