[0, n - 1]
κΉμ§μ λ
Έλλ‘ κ΅¬μ±λ treeκ° μ μμ μΌλ‘ ꡬμ±λμλμ§ νμΈνλ λ¬Έμ μ΄λ€.
- λ§μΌ treeκ° μ μμ μΌλ‘ ꡬμ±λμ΄μλ€λ©΄
leftChild
, rightChild
μ μλ λ
Έλ λ²νΈμ ν©μ [0, n - 1]
λ²μμ μλ λ
Έλ μ€ μμμ μ«μ νλκ° λΉ μ§ μ«μμ ν©μ΄ λλ€.
- κ·Έλ¦¬κ³ μ¬κΈ°μ λΉ μ§ μ«μ = λ£¨νΈ λ
Έλκ° λλ―λ‘ child λ
Έλ λ²νΈμ ν©μ ν΅ν΄μ λ£¨νΈ λ
Έλμ λ²νΈλ₯Ό ꡬν μ μλ€.
- κ·Έλ¦¬κ³ μ΄λ κ² κ΅¬ν΄μ§ λ£¨νΈ λ
Έλ λ²νΈκ° μ μ λ²μλ₯Ό μ΄κ³Όνλμ§ νμΈνλ€.
- λ£¨νΈ λ
Έλλ₯Ό κΈ°μ€μΌλ‘ νμνλ©΄μ λͺ¨λ λ
Έλλ₯Ό νμνλμ§ κ²μ¬νλ€.
class Solution {
public:
bool check(int rootNode, vector<int>& leftChild, vector<int>& rightChild) {
vector<bool> visited(leftChild.size(), false);
vector<int> s;
int count = 0;
s.push_back(rootNode);
while (!s.empty()) {
auto i = s.back();
s.pop_back();
if (visited[i]) return false;
visited[i] = true;
++count;
if (leftChild[i] != -1)
s.push_back(leftChild[i]);
if (rightChild[i] != -1)
s.push_back(rightChild[i]);
}
return count == leftChild.size();
}
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
if (n == 1) return true;
int nodeSum = 0;
for (auto i : leftChild) {
if (i != -1) nodeSum += i;
}
for (auto i : rightChild) {
if (i != -1) nodeSum += i;
}
int expectedSum = (n - 1) * n / 2;
int rootNode = expectedSum - nodeSum;
if (rootNode < 0 || rootNode >= n) return false;
return check(rootNode, leftChild, rightChild);
}
};