【问题标题】:Find the position of a give data in the inorder traversal of a binary search tree在二叉搜索树的中序遍历中找到给定数据的位置
【发布时间】:2015-08-21 12:55:39
【问题描述】:

我在二叉搜索树的中序遍历中搜索数据的位置(索引号)。

void inorder(struct node *root) {    
  if(!root)
      return NULL;
  inorder(root->left);
  cout<<root->data;
  inorder(root->right);
}

如何修改此函数以获取给定数字的位置。

【问题讨论】:

  • 首先,请根据stackoverflow的政策格式化代码。

标签: algorithm data-structures tree binary-search-tree inorder


【解决方案1】:

你可以通过引用传递一个整数并在你的函数中增加它:

void inorder(struct node *root, int &position){    
    if(!root)
        return NULL;
    inorder(root->left, position);
    position++;
    cout<<position<<": "<<root->data;
    inorder(root->right, position);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    相关资源
    最近更新 更多