gpt4 book ai didi

algorithm - 填充树的所有节点的数据字段

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:33:14 25 4
gpt4 key购买 nike

A node of a binary tree has two pointers, 'left' and 'right', and two data fields, 'leftcount' and 'rightcount'. 'leftcount' specifies the number of nodes in the left subtree of the node, and 'rightcount' specifies the number of nodes in the right subtree of the node. Write an algorithm to populate the data fields of all the nodes of the tree.

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

最佳答案

这应该有效(我相信):

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;
}

关于algorithm - 填充树的所有节点的数据字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10156247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com