编程练习-二叉树(二叉树转双向链表)

1.把二元查找树转变成排序的双向链表 ****
 题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
   10
  / /
  6  14
 / / / /
4  8 12 16
 转换成双向链表
4=6=8=10=12=14=16。
 
 首先我们定义的二元查找树 节点的数据结构如下:
 struct BSTreeNode
{
  int m_nValue; // value of node
  BSTreeNode *m_pLeft; // left child of node
  BSTreeNode *m_pRight; // right child of node

};

解答:

先序遍历,对于每个节点,它的做指针指向左子树的最右节点(左子树的最大节点),他的右指针指向右子树的最左节点(右子树的最小节点),首先要定位到这两个节点,但这两个节点的指针先不做调整,递归调用左子树和右子树后,再调整这两个节点,以保证程序能够正常执行,如果提前调整了这两个节点,左右子树的树结构就破坏了,运行会死循环出错。

下面是代码: 

#include <stdio.h>
struct TreeNode {
  int value_;
  TreeNode* left_;
  TreeNode* right_;
};
void Insert(TreeNode* &root, const int key) {
  if (root == NULL) {
    root = new TreeNode;
    root->value_ = key;
    root->left_ = NULL;
    root->right_ = NULL;
    return;
  }
  if (key >= root->value_) {
    Insert(root->right_, key);
  } else {
    Insert(root->left_, key);
  }
}
void Print(TreeNode* root) {
  if (root) {
    printf("%d ", root->value_);
  } else {
    return;
  }
  if (root->left_) {
    Print(root->left_);
  }
  if (root->right_) {
    Print(root->right_);
  }
}
void ConvertToList(TreeNode*& root) {
  TreeNode* left;
  TreeNode* right;
  if (root) {
    left = root->left_;
    right = root->right_;
    TreeNode* left_most_right = left;
    while (left_most_right && left_most_right->right_) {
      left_most_right = left_most_right->right_;
    }
    root->left_ = left_most_right;
    if (left) {
      ConvertToList(left, head);
    }
    if (left_most_right) {
      left_most_right->right_ = root;
    }
    TreeNode* right_most_left = right;
    while (right_most_left && right_most_left->left_) {
      right_most_left = right_most_left->left_;
    }
    root->right_ = right_most_left;
    if (right) {
      ConvertToList(right, head);
    }
    if (right_most_left) {
      right_most_left->left_ = root;
    }
  }
}
int main(int argc, char** argv) {
  int data[] = {10, 6, 14, 4, 8, 12, 16, 22, 3, 25, 74, 1, 18, 62, 7, 5};
  TreeNode* root = NULL;
  size_t size = sizeof(data)/sizeof(int);
  for (int i = 0; i < size; ++i) {
    Insert(root, data[i]);
  }
  //  Print(root);
  TreeNode * indexer = root;
  ConvertToList(root);
    while (indexer) {
    printf("%d ", indexer->value_);
    indexer = indexer->right_;
  }
  if (root) {
    indexer = root->left_;
  }
  while (indexer) {
    printf("%d ", indexer->value_);
    indexer = indexer->left_;
    }
}
参考文献:

http://www.360doc.com/content/07/0228/15/11586_379396.shtml

http://blog.csdn.net/qjt_uestc/article/details/6618022



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值