题解 | #二叉搜索树与双向链表#

二叉搜索树与双向链表

https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

/**
 * 
 * @param pRootOfTree TreeNode类 
 * @return TreeNode类
 */


#include <stdio.h>
void visit(struct TreeNode* tree,struct TreeNode** resul,int* count){
    resul[*count] = tree;
    (*count)++;
}
void InOrder(struct TreeNode* pRootOfTree,struct TreeNode** resul,int* count){
    if(pRootOfTree){
        InOrder(pRootOfTree->left,resul,count);
        visit(pRootOfTree,resul,count);
        InOrder(pRootOfTree->right,resul,count);
    }
}
struct TreeNode* Convert(struct TreeNode* pRootOfTree ) {
    // write code here
    int count = 0;
  //开辟指向链表的链表
    struct TreeNode** resul_li = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 100);
  //注意每个链表还要开辟空间
    for(int i =0;i<100;i++){
        resul_li[i] = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    }
    InOrder(pRootOfTree,resul_li,&count);
    for(int i=0;i<count;i++){
        resul_li[i]->right = resul_li[i+1];
        resul_li[i+1]->left = resul_li[i];
    }
    if(count==0) return NULL;
    resul_li[0]->left = NULL;
    resul_li[count-1]->right=NULL;
    return resul_li[0];
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务