繁体   English   中英

二叉树旋转函数,不包含引用指针,指针到指针或返回新节点的函数

[英]Binary tree rotate function without reference-to-pointer, pointer-to-pointer, or the function returning the new node

我必须在C ++中实现以下类的实现:

struct Node {
  Node* parent;
  Node* left;
  Node* right;
  std::string name;
};

class BinaryTree {
 public:
  BinaryTree();
  std::string ToString() const;  
  void RotateLeft(Node* node);
  void RotateRight(Node* node);
  void MakePerfect();
 private:
  void CreateVine();
  void MakePerfectFromVine();
 private:
  Node *root;
};

此类实现DSW算法以使二叉树完美(所有级别均已满,最后一级除外)

我已经完成了一个可行的实现,我对其进行了测试,并且一切似乎都很好,但是我不得不这样更改旋转功能:

  void RotateLeft(Node*& node);
  void RotateRight(Node*& node);

不幸的是,将任务设置给我的人说我禁止更改它们。 但是未更改的功能不起作用。 我在CreateVine()MakePerfectFromVine()使用它们:

void CreateVine() {
    Node *current = root;
    while(current != NULL)
        if(current->left != NULL){
            current=current->left;
            rotateRight(current);               
        }
        else
            current = current->right;

}

在此片段中,指针current指向树中的一个节点。 旋转节点后,它将更改其父节点和/或左子节点和/或右子节点,但是current节点将指向具有旧信息的旧节点。 为了使对旋转函数所做的更改反映在旋转函数之外,我必须使用引用指向指针,指针指向指针,否则函数本身必须返回节点;

解决这个问题的唯一方法是,如果我知道二叉树不允许重复的元素,则在旋转节点后,我将搜索其字符串值并将其设置为current值,但我没有确定二叉树是否不允许重复元素,这会增加算法的时间复杂度。

有什么方法可以避免使用引用指针和指针指向指针?

除了可能需要考虑其他问题的树的根以外,还可以通过额外的间接级别获得指向树内给定节点的指针:

Node **pp;
if (node->parent->left == node)
   pp = &node->parent->left;
else
   pp = &node->parent->right;

因此,您实际上可以维护算法,而只需解析函数内部的引用即可 请注意,这是一个草图,您将必须检查根( parent==0 )并在那里进行不同的操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM