题目描述:
二叉树上有 n 个节点,按从 0 到 n - 1 编号,其中节点 i 的两个子节点分别是 leftChild[i] 和 rightChild[i]。
只有 所有 节点能够形成且 只 形成 一颗 有效的二叉树时,返回 true;否则返回 false。
如果节点 i 没有左子节点,那么 leftChild[i] 就等于 -1。右子节点也符合该规则。
注意:节点没有值,本问题中仅仅使用节点编号。
示例 1:
输入:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
输出:true
示例 2:
输入:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
输出:false
示例 3:
输入:n = 2, leftChild = [1,0], rightChild = [-1,-1]
输出:false
示例 4:
输入:n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1]
输出:false
提示:
1 <= n <= 10^4
leftChild.length == rightChild.length == n
-1 <= leftChild[i], rightChild[i] <= n - 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-tree-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
其实我的代码是有问题的:如果不是以0为根节点,那么就会出现问题i但是当时ac了
class Solution {
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
Set<Integer> set = new HashSet<> ();Queue<Integer> queue = new LinkedList<> ();queue.offer (0);set.add (0);while (!queue.isEmpty ()){
int size = queue.size ();for (int i = 0; i < size; i++) {
Integer poll = queue.poll ();
// 做孩子int left = leftChild[poll];int right = rightChild[poll];if(left != -1){
if(set.contains (left)){
return false;}set.add (left);queue.offer (left);}if(right != - 1){
if(set.contains (right)){
return false;}set.add (right);queue.offer (right);}}}return set.size () == n;}
}
看看别人的思路:
// 验证二叉树public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
int[] in = new int[n];for (int i = 0; i < n; i++) {
if (leftChild[i] != -1) in[leftChild[i]]++;if (rightChild[i] != -1) in[rightChild[i]]++;}int count0 = 0;int countOther = 0;for (int temp : in) {
if (temp == 0) count0++;if (temp > 1) countOther++;}return count0 == 1 && countOther == 0;}作者:challengerzsz
链接:https://leetcode-cn.com/problems/validate-binary-tree-nodes/solution/zhuan-huan-cheng-tu-de-si-xiang-ji-suan-mei-ge-jie/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。