【问题标题】:Job interview question made harder, check all except root?求职面试问题变得更难,检查除根以外的所有内容?
【发布时间】:2021-07-31 10:01:12
【问题描述】:

我在一次采访中遇到了这个问题,虽然起初看起来很容易,但当我深入研究时,对于大量的边缘情况来说,这对我来说几乎是不可能的。

要求:

想象一棵树,其中每个节点可以有 0 到 10 个孩子,每个孩子都有自己的权重,编写一个执行以下操作的函数:

  1. 如果根没有子节点,则返回 -1;
  2. 否则,返回树的所有子节点(根节点除外)的权重总和。

我尝试了类似的方法:

int my_func(node *root) {
    if (root->isleaf())
    {
        return -1;
    }
    int result = 0;
    for (int i = 0; i < root->num_of_children(); ++i)
    {
        result += my_func(root->child[i]);
    }
    return result;
}

但这真的很糟糕,原因有两个:

  1. 我并不是所有孩子的体重相加。

  2. 当我到达叶子孩子时,我正在求和 -1 而我应该加 0。

【问题讨论】:

  • 编写对所有节点、root和all的权重求和的函数;这只是一个简单的递归。然后编写另一个调用第一个函数的函数,然后从该总数中减去根的权重(或者,对每个孩子调用第一个并将结果相加)。第二个函数还将处理仅根树的特殊情况。
  • c 与此有什么关系??我可能会让你在工作面试中失败,因为不知道有什么不同。另外,您的代码中关于 c++11 的具体内容是什么?我没有看到任何相关性,将删除标签。
  • @πάνταῥεῖ 我确信有更好的方法可以告诉他 C 标签不相关。
  • 根据文字描述,这个函数应该总是返回一个负值。

标签: c++ algorithm tree


【解决方案1】:

创建一个新函数,委托给您的函数处理根没有子节点的情况,并在计算总和后删除根的权重。您还忘记在原始函数中添加权重。您可以通过在添加其余部分之前将 result 设置为 root-&gt;weight 来解决此问题。

int sumOfWeightsExceptRoot(node* root) {
  if (!root || root->isLeaf())
    return -1;
  return my_func(root) - root->weight;
}

int my_func(node* root) {
  if (!root)
    return 0;
  int result = root->weight;
  for (int i = 0; i < root->num_of_children(); ++i) {
    result += my_func(root->child[i]);
  }
  return result;
}

迭代版本:

int sumOfWeightsExceptRoot(node* root) {
  if (!root || root->isLeaf())
    return -1;

  std::stack<node*> s;
  s.push(root);

  int result = -root->weight;
  while (!s.empty()) {
    node* ptr = s.top(); s.pop();
    result += ptr->weight;
    for (int i = 0; i < ptr->num_of_children(); i++) {
      s.push(ptr->child[i]);
    }
  }
  return result;
}

【讨论】:

  • 如果我想在一个函数中使用它们怎么办?
  • @mr_calc 那么它需要是一个非递归函数。您将使用 std::stack 并遍历执行相同操作的节点。我会发布它。
  • @mr_calc 已发布。
猜你喜欢
  • 2021-09-15
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 2015-08-01
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
相关资源
最近更新 更多