微软一道笔试题目

本文深入解析了一种将二叉树转换为双向链表的算法实现过程,包括初始化、中序遍历及节点链接操作,并提供了源代码实例。讨论了算法效率与优化思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此题目是冲一篇博客上面看到的http://blog.csdn.net/v_JULY_v/article/details/6057286,最后我下载了他的解答,发现有错误,准备直接看他解答的博客,结果没有发现,所以自己就在他的思想上,进行了,重新编写


题目是这样的,

一下是我的源代码

数据没有完全一样,在创建二叉树的时候,没有优化,懂那个意识就可了我觉得



#include <iostream>


struct BSTreeNode{
int m_Value;
BSTreeNode * m_pLeft;
BSTreeNode * m_pRight;
}; 


BSTreeNode *head,*tail;


void InitTree(BSTreeNode * root){
BSTreeNode *tmp1 = new BSTreeNode;

tmp1->m_Value = 6;
tmp1->m_pLeft = NULL;
tmp1->m_pRight = NULL;
root->m_Value =10;
root->m_pLeft = tmp1;


BSTreeNode *tmp2 = new BSTreeNode;


tmp2->m_Value = 14;
tmp2->m_pLeft = NULL;
tmp2->m_pRight = NULL;
root->m_pRight = tmp2;




BSTreeNode *tmp3 = new BSTreeNode;


tmp3->m_pLeft = NULL;
tmp3->m_pRight = NULL;
tmp3->m_Value = 4;


BSTreeNode *tmp4 = new BSTreeNode;


tmp4->m_pLeft = NULL;
tmp4->m_pRight = NULL;
tmp4->m_Value = 8;


tmp1->m_pLeft =tmp3;
tmp1->m_pRight = tmp4;


BSTreeNode *tmp5 = new BSTreeNode;
tmp5->m_pLeft = NULL;
tmp5->m_pRight = NULL;
tmp5->m_Value = 12;
tmp4->m_pLeft = tmp5;


return;

}


void Trival(  BSTreeNode * root ) 
{




if (head == NULL)
{
head = root;
tail = root;
}
else{
tail->m_pRight = root;
root->m_pLeft = tail;
tail = root;
}


return;
}


void helper ( BSTreeNode *root){


if (root == NULL)
return;
helper( root->m_pLeft);
Trival( root);
helper( root->m_pRight);
return ;
}




BSTreeNode * treeToLinkedList(BSTreeNode * root){

helper(root);
return head;
}




int main(int argc, _TCHAR* argv[])
{
BSTreeNode *root = new BSTreeNode;
InitTree(root);


treeToLinkedList(root);


for (int i =0; i<6; ++i )
{
//顺时针测试
/*std::cout<<head->m_Value<<std::endl;
head = head->m_pRight;*/
//逆时针测试
std::cout<<tail->m_Value<<std::endl;
tail = tail->m_pLeft;
}
return 0;
}



整个转换过程,其实就是一个二叉树的中序遍历,如果大家有个更好的方式,可以探讨,由于没有写过几次博客,所以就这个样子


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值