quark

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

算法题目链接:http://bbs.csdn.net/topics/350093707

题目

// 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
// };

分析

本质上应该属于二叉树遍历的问题,中序遍历。因为不能创建新的节点,所以只能用递归。

代码

struct BSTreeNode
{
    int          m_nValue; // value of node
    BSTreeNode  *m_pLeft;  // left child of node
    BSTreeNode  *m_pRight; // right child of node
};

BSTreeNode* Convert(BSTreeNode* node, BSTreeNode** nodeHead)
{
    if (node->m_pLeft)
    {
        BSTreeNode* bottomRight = Convert(node->m_pLeft, nodeHead);
        bottomRight->m_pRight = node;
        node->m_pLeft = bottomRight;
    }
    else
    {
        if (!*nodeHead)
        {
            *nodeHead = node;
        }
    }

    if (node->m_pRight)
    {
        BSTreeNode* bottomRight = Convert(node->m_pRight, nodeHead);
        node->m_pRight->m_pLeft = node;
        return bottomRight;
    }
    else
    {
        return node;
    }
}
posted on 2014-04-16 10:56  QuarkZ  阅读(212)  评论(0编辑  收藏  举报