There the binary tree n
nodes, from the press 0
to the n - 1
number in which a node i
two child nodes respectively leftChild[i]
and rightChild[i]
.
Only all nodes can be formed and only form a valid binary tree, returns true
; otherwise false
.
If the node i
is not left child, then leftChild[i]
it is equal -1
. Right child is also consistent with the rule.
Note: The node has no value, this problem using only the node number.
Example 1:
Input: n-=. 4, leftChild = [. 1,-1,3, -1], rightChild = [2, -1, -1, -1] Output: to true
Example 2:
Input: n-=. 4, leftChild = [. 1,-1,3, -1], rightChild = [2,3, -1, -1] Output: to false
Example 3:
Input: n-2 =, leftChild = [1,0], rightChild = [-1, -1] Output: to false
Example 4:
Input: n-=. 6, leftChild = [. 1, -1,-1,4-, -1, -1], rightChild = [2, -1,-1,5, -1, -1] Output: to false
prompt:
1 <= n <= 10^4
leftChild.length == rightChild.length == n
-1 <= leftChild[i], rightChild[i] <= n - 1
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
class Solution {
public:
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
vector<int> inDegree(n,0);
for(int i=0;i<n;i++){
if(leftChild[i]!=-1) inDegree[leftChild[i]]++;
if(rightChild[i]!=-1) inDegree[rightChild[i]]++;
}
int root = -1;
for(int i=0;i<n;i++){
if(inDegree[i]!=0)continue;
if(root != -1)return false;
root = i;
}
if(root == -1 ) return false;
queue<int> que;
vector<bool> vi(n,false);
vi[root]=true;
que.push(root);
while(!que.empty()){
int q = que.front();
que.pop();
if(leftChild[q]!=-1){
if(vi[leftChild[q]]==true) return false;
vi[leftChild[q]]=true;
que.push(leftChild[q]);
}
if(rightChild[q]!=-1){
if(vi[rightChild[q]]==true) return false;
vi[rightChild[q]]=true;
que.push(rightChild[q]);
}
}
return all_of(vi.begin(),vi.end(),[](const int &a){return a==1;});
}
};
int main(){
//freopen("D:\\YJ.txt","r",stdin);
int n;
cin>>n;
vector<int> leftChild(n,0),rightChild(n,0);
for(int i=0;i<n;i++)cin>>leftChild[i];
for(int i=0;i<n;i++)cin>>rightChild[i];
Solution solution;
bool res = solution.validateBinaryTreeNodes(n, leftChild, rightChild);
cout<<res;
return 0;
}