• 创建排序二叉树


    创建排序二叉树:插入时,从根开始遍历。

    如果比根小,判断有没有左节点,有则向左走,没有则将该节点作为左节点。

    如果比根大,判断有没有右节点,有则向右走,没有则将该节点作为右节点。

    初级版代码:

    Tree* Create(int * arr,int len)
    {
        Tree* pRoot = (Tree*)malloc(sizeof(Tree));
        pRoot->val = arr[0];
        pRoot->pleft = NULL;
        pRoot->pright = NULL;
        for(int i = 1; i < len;i++)
        {
            Tree* tree = (Tree*)malloc(sizeof(Tree));
            tree->val = arr[i];
            tree->pleft = NULL;
            tree->pright = NULL;
            Tree* tmp = pRoot;
            while(1)
            {
                if(arr[i] == tmp->val)
                    return NULL;
                else if(arr[i] < tmp->val)
                    if(tmp->pleft != NULL)
                        tmp = tmp->pleft;
                    else 
                        {tmp->pleft = tree;
                        break;}
                else if(arr[i] > tmp->val)
                    if(tmp->pright != NULL)
                        tmp = tmp->pright;
                    else
                    {    tmp->pright = tree;
                    break;}
            }
        }
        return pRoot;
    }

    升级版代码:

    void InsertNode(BinaryTree **pTree,int nNum)
    {
        BinaryTree *pTemp = NULL;
        pTemp = (BinaryTree*)malloc(sizeof(BinaryTree));
        pTemp->nValue = nNum;
        pTemp->pLeft = NULL;
        pTemp->pRight = NULL;
        
        //树空
        if(*pTree == NULL)
        {
            *pTree = pTemp;
            return;
        }
    
        BinaryTree *pNode = NULL;
        pNode = *pTree;
    
        while(1)
        {
            if(pNode->nValue > nNum)
            {
                //去左侧
                if(pNode->pLeft == NULL)
                {
                    pNode->pLeft = pTemp;
                    return;
                }
    
                pNode = pNode->pLeft;
            }
            else if(pNode->nValue < nNum)
            {
                //右侧
                if(pNode->pRight == NULL)
                {
                    pNode->pRight = pTemp;
                    return;
                }
                pNode = pNode->pRight;
            }
            else
            {
                //相等
                printf("error.
    ");
                return;
            }
        }
    }
    
    BinaryTree *CreateBST(int arr[],int nLength)
    {
        if(arr == NULL || nLength <=0)return NULL;
        
        BinaryTree *pTree = NULL;
        int i;
        for(i = 0;i<nLength;i++)
        {
            InsertNode(&pTree,arr[i]);
        }
        return pTree;
    }
  • 相关阅读:
    JVM内存逃逸
    SQL中游标的使用
    配置JAVA环境变量中CLASSPATH变量的作用
    什么是单点登录?单点登录的三种实现方式
    oracle中 connect by prior 递归算法
    test
    mac idea 常见错误记录
    mac 常用操作命令记录
    mac idea 常用快捷键记录
    运行maven install命令时出现错误(BUILD FAILURE)
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/9028972.html
Copyright © 2020-2023  润新知