【问题标题】:Recursively add 1 to all nodes in a BST except node with SMALLEST data递归地将 BST 中的所有节点加 1,但具有 SMALLEST 数据的节点除外
【发布时间】:2017-08-09 07:50:45
【问题描述】:

我正在尝试为每个节点的数据添加 +1,但编号最小的节点除外。到目前为止,我的实现并不正确,我在递归调用中迷失了方向。我的代码在某些情况下添加不正确,并且在必要时未添加。我理解要找到最小的数据,我们去一直连接到左边的节点(8)在这种情况下,我是否缺少某些测试条件?

Given a data set: 8, 14, 24, 29, 31, 35, 46, 58, 62,85, 95

Expected results: 8, 15, 25, 30, 32, 36, 47, 59, 63, 86, 96
Actual results: 9, 14, 25, 29, 32, 36, 46, 59, 63, 85, 96

struct node
{

 node * left;
 node * right;
 int data;

};

int add1(node * root) 
{

    if(!root) return 0;    
    add1(root->left); //go left

    if(!root->left)  { //if left is NULL
        if(root->right) //check if there is a right child
            add1(root->right); //go to that node
        else
            return 0;
    }

    root->data += 1;    //add 1 to node
    add1(root->right); //go right

return 1;
}

int main()
{
node * root = NULL;
build(root); //inserts data set into our tree

display(root);
add1(root);
display(root);

return 0;

}

【问题讨论】:

  • 对不起,你的意思是添加我节点的结构吗?
  • 是的节点声明和初始化

标签: c++ recursion binary-search-tree


【解决方案1】:

您可以下降树,跟踪您是否可能是最左边的节点。如果您曾经右转到达某个节点,则该节点不能位于最左侧。如果您可能是最左边的节点,并且您没有左孩子,那么您最左边的节点。其他的都加了 1。

void add1(root* node, bool mightbeLeftmost=true)
{
    if(!root) return;
    if(!mightbeLeftmost || root->left != nullptr) ++(root->data);
    add1(root->left, mightbeLeftmost);
    add1(root->right, false);
}

int main()
{
    //define list
    ...
    add1(root, true);
}

【讨论】:

  • 这是一个二叉搜索树。您无需遍历整个树即可发现最小值。最低值始终是树中最左边的值。
  • 哦,是的,我错过了那部分。会调整
【解决方案2】:

这是一个具有额外好处的函数解决方案:除了递增除最小值之外的所有值,它还返回最小 BST 值。如果最小值不是唯一的,它也可以工作。

#include <limits.h>

...

int add1(struct node* root)
{
        static int min;

        if (root == NULL)
          return INT_MAX;

        int lval = add1(root->left);

        // Check if it's the leftmost node to set min
        if (lval == INT_MAX)
            min = root->data;

        add1(root->right);

        if (root->data != min)
            root->data++;

        return min;
}

【讨论】:

    猜你喜欢
    • 2012-10-07
    • 2020-03-18
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多