二叉查找树转化为双向链表


#include <iostream>
#include <queue>

using namespace std;


struct node{
  int data;
  node *left;
  node *right;
  node *prev;
  node *next;

  node(const int &x, node *l = NULL, node *r = NULL, node *p = NULL, node *n = NULL):data(x), left(l), right(r), prev(p), next(n){}
  ~node(){}
};

//中序遍历
void mid_traverse(node *root){
  if (root == NULL)
    return;

  if (root->left != NULL)
    mid_traverse(root->left);

  cout << root->data <<endl;

  if (root->right != NULL)
    mid_traverse(root->right);
}

//队列实现
void tree_to_bilist(node *root, queue<node *> &st){
  if (root == NULL)
    return;

  if (root->left != NULL)
    tree_to_bilist(root->left, st);

  st.push(root);

  if (root->right != NULL)
    tree_to_bilist(root->right, st);
}

//递归实现
void tree_list_core(node *root, node *&last){
  // 处理左子树
  if (root->left != NULL){
    tree_list_core(root->left, last);
  }

  // 连接当前结点root到左子树
  if (last != NULL){
    last->right = root;
  }
  root->left = last;

  // 处理右子树
  last = root;
  if (root->right != NULL)  // root->right视为当前结点
    tree_list_core(root->right, last);
}

node *tree_to_bilist_recursively(node *root){
  if (root == NULL)
    return NULL;

  node *last = NULL;
  tree_list_core(root, last);

  node *head = root;
  while (head->left != NULL)
    head = head->left;

  return head;
}


int main(){
  node *root = new node(10);
  node *tmp;
  tmp = new node(6);
  root->left = tmp;
  tmp = new node(4);
  root->left->left = tmp;
  tmp = new node(8);
  root->left->right = tmp;
  tmp = new node(14);
  root->right = tmp;
  tmp = new node(12);
  root->right->left = tmp;
  tmp = new node(16);
  root->right->right = tmp;

  //中序遍历
  mid_traverse(root);
  cout << endl;

  //队列实现
  queue<node *> st;
  tree_to_bilist(root, st);

  while (!st.empty()){
    cout << st.front()->data << endl;
    st.pop();
  }
  cout << endl;

  //递归实现
  node *head = tree_to_bilist_recursively(root);
  node * pNode = head;
  while (pNode != NULL){
    cout << pNode->data << endl;
    pNode = pNode->right;
  }


  int ttt = 0;

  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值