How to remove child nodes of a tree with one child node

I have an array for preliminary traversal of the tree (node ​​values ​​- depth values). All I want to do is minimize the tree by removing child nodes that have only one child.

As an example (a tree with maximum depth = 3), the problem presented here is

Input array: [0, 1, 2, 3, 3, 1, 2, 3]
Output array: [0, 1, 2, 2, 1]

How should the algorithm be?

+4
source share
2 answers

A simple, medium-sized O (nlog (n)) algorithm arises from an attack on a problem using the divide and conquer approach.

input_level = 0, output_level=0, left=0, right=n-1.

input_level+1 A [left, right]. node. , output_level . , "" node (.. ), left 1 . , output_level, output_level 1 , . input_level .

A=[0, 1, 2, 3, 3, 1, 2, 3] 1, 1 5. 0, output_level current_level 1 : [1, 4] [5, 7].

- O (n 2) ( , ), O (nlog (n)) , n- O (log (n)).

+1

O (N) . , .

#include <algorithm>
#include <iostream>
#include <stack>
#include <tuple>
#include <utility>
#include <vector>

void mark_nodes(const std::vector<unsigned>& tree,
                std::vector<bool>& mark) {
  // {depth, index, mark?}
  using triple = std::tuple<unsigned, unsigned, bool>;
  std::stack<triple> stk;
  stk.push({0, 0, false});
  for (auto i = 1u; i < mark.size(); ++i) {
    auto depth = tree[i];
    auto top_depth = std::get<0>(stk.top());
    if (depth == top_depth) {
      stk.pop();
      if (stk.size()) std::get<2>(stk.top()) = false;
      continue;
    }
    if (depth > top_depth) {
      std::get<2>(stk.top()) = true;
      stk.push({depth, i, false});
      continue;
    }
    while (std::get<0>(stk.top()) != depth) {
      mark[std::get<1>(stk.top())] = std::get<2>(stk.top());
      stk.pop();
    }
    mark[std::get<1>(stk.top())] = std::get<2>(stk.top());
    stk.pop();
    if (stk.size()) std::get<2>(stk.top()) = false;
    stk.push({depth, i, false});
  }
  mark[0] = false;
}

std::vector<unsigned> trim_single_child_nodes(
    std::vector<unsigned> tree) {
  tree.push_back(0u);
  std::vector<bool> mark(tree.size(), false);
  mark_nodes(tree, mark);
  std::vector<unsigned> ret(1, 0);
  tree.pop_back();
  mark.pop_back();
  auto max_depth = *std::max_element(tree.begin(), tree.end());
  std::vector<unsigned> depth_map(max_depth + 1, 0);
  for (auto i = 1u; i < tree.size(); ++i) {
    if (mark[i]) {
      if (tree[i] > tree[i - 1]) {
        depth_map[tree[i]] = depth_map[tree[i - 1]];
      }
    } else {
      if (tree[i] > tree[i - 1]) {
        depth_map[tree[i]] = depth_map[tree[i - 1]] + 1;
      }
      ret.push_back(depth_map[tree[i]]);
    }
  }
  return ret;
}

int main() {
  std::vector<unsigned> input = {0, 1, 2, 3, 3, 1, 2, 3};
  auto output = trim_single_child_nodes(input);
  for (auto depth : output) {
    std::cout << depth << ' ';
  }
}
0

Source: https://habr.com/ru/post/1626997/


All Articles