【问题标题】:Populate the data field of all the nodes of the tree填充树的所有节点的数据字段
【发布时间】:2012-04-14 18:37:26
【问题描述】:

二叉树的一个节点有两个指针“left”和“right”,以及两个数据字段“leftcount”和“rightcount”。 “leftcount”指定节点左子树中的节点数,“rightcount”指定节点右子树中的节点数。编写一个算法来填充树的所有节点的数据字段。

我在一次采访中被问到这个问题。我想出了一个基于树的后序遍历的解决方案。有人可以指导我吗?

【问题讨论】:

  • 如果您已经有了解决方案,那么您对 ​​SO 观众的问题是什么?
  • @OliCharlesworth:感谢您的回复。当有人问我是否可以按照我建议的任何其他方式进行操作时,我已经发布了这篇文章。

标签: algorithm data-structures tree


【解决方案1】:

这应该可行(我相信):

int populateCounters(Node* node) {
    if(node == NULL) return 0;
    node->leftCount = populateCounters(node->left);
    node->rightCount = populateCounters(node->right);
    return node->leftCount + node->rightCount + 1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多