二叉树上的最大堆

时间:2013-12-10 19:06:35

标签: c heap binary-tree

我正在尝试创建一个可以创建最大堆树的函数。

问题是 我希望我的函数返回这棵树的根,但我不知道该怎么做。 我认为这里的行(1)和这里的行(2)将使函数在插入之前返回最后一个节点,我想不出一种简单的方法让它返回树的根。

typedef struct node{
  int n;
  struct node* right;
  struct node* left;
}node; 

node * f(node* root, int v){
  node* p;
  if(!root){ //creating new node;
    p = malloc(sizeof(node));
    p->n = v;
    p->right = NULL;
    p->left = NULL;
    return p;
  }    

  if(v > root->n){ //if v is greater than the node, they'll be swapped.
    int aux = root->n;
    root->n = v;
    return f(root->right, aux); //here(1) 
  }

  //if v is smaller than the node, f will be called to the left node.
  if(v < root->n){ 
    int aux = root->n;
    return f(root->left, aux); //here(2)
  }

  return root;
}

1 个答案:

答案 0 :(得分:0)

要使函数始终返回根节点,我会将//here条评论的两行更改为:

f(root->right, aux); //here(1) 
return root;

f(root->left, aux); //here(2) 
return root;
相关问题