Skip to content

Commit

Permalink
Validate Binary Tree Nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 17, 2023
1 parent 9e7e276 commit 4e28c20
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,7 @@ add_task(valid-perfect-square)
add_task(valid-sudoku)
add_task(valid-triangle-number)
add_task(validate-binary-search-tree)
add_task(validate-binary-tree-nodes)
add_task(validate-stack-sequences)
add_task(verifying-an-alien-dictionary)
add_task(water-and-jug-problem)
Expand Down
1 change: 1 addition & 0 deletions solutions/validate-binary-tree-nodes/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_validate_binary_tree_nodes test.cpp)
52 changes: 52 additions & 0 deletions solutions/validate-binary-tree-nodes/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#pragma once

#include <vector>

class DisjointSets {
public:
explicit DisjointSets(int size) : parents_(size), count_(size) {
for (int i = 0; i < size; ++i) {
parents_[i] = i;
}
}

int Count() { return count_; }

int Parent(int i) {
if (parents_[i] != i) {
parents_[i] = Parent(parents_[i]);
}
return parents_[i];
}

bool Merge(int parent, int child) {
if (child != Parent(child) || Parent(child) == Parent(parent)) {
return false;
}

--count_;
parents_[Parent(child)] = Parent(parent);
return true;
}

private:
std::vector<int> parents_;
int count_;
};

class Solution {
public:
static bool validateBinaryTreeNodes(int n, const std::vector<int> &left,
const std::vector<int> &right) {
DisjointSets sets(n);
for (const auto &children : {left, right}) {
for (int parent = 0; parent < n; ++parent) {
const auto child = children[parent];
if (child != -1 && !sets.Merge(parent, child)) {
return false;
}
}
}
return sets.Count() == 1;
}
};
45 changes: 45 additions & 0 deletions solutions/validate-binary-tree-nodes/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
int n;
std::vector<int> leftChild;
std::vector<int> rightChild;
bool expected;
};

std::vector<TestCase> test_cases{
{
.n = 4,
.leftChild{1, -1, 3, -1},
.rightChild{2, -1, -1, -1},
.expected = true,
},
{
.n = 4,
.leftChild{1, -1, 3, -1},
.rightChild{2, 3, -1, -1},
.expected = false,
},
{
.n = 2,
.leftChild{1, 0},
.rightChild{-1, -1},
.expected = false,
},
{
.n = 4,
.leftChild{1, 0, 3, -1},
.rightChild{-1, -1, -1, -1},
.expected = false,
},
};

for (const auto &[n, leftChild, rightChild, expected] : test_cases) {
const auto actual =
Solution::validateBinaryTreeNodes(n, leftChild, rightChild);
REQUIRE(expected == actual);
}
}

0 comments on commit 4e28c20

Please sign in to comment.