1361. Validate Binary Tree Nodes

  • [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); } };