• 【算法Everyday】第一日 二叉查找树转双向链表


    算法题目链接: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;
        }
    }
  • 相关阅读:
    Java面向对象XMind
    使用idea插件JRebel热部署的坑
    Mysql小技巧(多行数据合并+模糊查询
    JRebel安装使用
    Shiro(三) 权限管理 假数据
    Shiro(二)通过shiro实现登录 连接数据库+集成Springboot
    Shiro(一)通过shiro实现登录
    poi实现Excel输出
    日志,注解切入点
    获取用户信息
  • 原文地址:https://www.cnblogs.com/quark/p/3668127.html
Copyright © 2020-2023  润新知