二叉搜索树转排序双向链表

来源:互联网 发布:科比谢幕战数据 编辑:程序博客网 时间:2024/05/22 06:42

例如   10
     /  /
    5   16   ===>  3<->5<->6<->10<->12<->16
   / /  /
  3  6  12
 
使用递归的方式
 
   1:  void build_dlist(node_t *node)
   2:  {
   3:      if (node->left) {
   4:          node_t * left = node->left;
   5:          while (left->right) {   //移动到双向链表的最右端,因为此处是链表的最大值。
   6:              left = left->right;
   7:          }
   8:          left->right = node;  //左子树链表最后节点指向父节点
   9:          node->left = left;   
  10:      }
  11:   
  12:      if (node->right) {
  13:          node_t * right = node->right;
  14:          while (right->left) {
  15:              right = right->left;
  16:          }
  17:          right->left = node;
  18:          node->right = right;
  19:      }
  20:  }
  21:   
  22:  void tree_to_list(node_t *node)
  23:  {
  24:      if (!node) {
  25:          return;
  26:      }
  27:      tree_to_list(node->left);
  28:      tree_to_list(node->right);
  29:      build_dlist(node);
  30:  }
.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }
原创粉丝点击