二叉树转双向链接表_LEARN FORM CSDN JULY

发现写个代码不容易,虽然很明白怎么回事,但是道和术是不同的,术需要懂得代码实现的细节,下面的代码,好几个地方一开始写错,死活运行不了,现在行了。。有问题请不吝赐教!
/*
 * BSTree2BILinkList.cpp
 *
 *  Created on: 2013-4-2
 *      Author: CJ
 */
#include<iostream>
using namespace std;

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

// @param  root The root node of the tree
// @return The head node of the converted list


void helper(BSTreeNode *& head, BSTreeNode *& tail, BSTreeNode *root){
	BSTreeNode *lt, *rh;
	//if root is NULL
	if(root == NULL){
		head = NULL;
		tail = NULL;
		return;
	}
	//recursion
	helper(head, lt, root->m_pLeft);
	helper(rh, tail, root->m_pRight);
	//if root is not NULL
	if(lt != NULL){
		lt->m_pRight = root;
		root->m_pLeft = lt;
	}else {
		head = root;
	}
	if(rh != NULL){
		rh->m_pLeft = root;
		root->m_pRight = rh;
	}else {
		tail = root;
	}
}
BSTreeNode* treeToLinkedList(BSTreeNode* root)
{
	BSTreeNode *head, *tail;
	helper(head,tail,root);
	return head;
}
int main()
{
	/*       A
	 *      / \
	 *      B  C
	 *     / \/ \
	 *    D  EF  G
	 *
	 *    转成双向链表
	 *    D=B=E=A=F=C=G
	 */
	BSTreeNode A; A.m_nValue = 4;
	BSTreeNode B; B.m_nValue = 2;
	BSTreeNode C; C.m_nValue = 6;
	BSTreeNode D; D.m_nValue = 1;
	BSTreeNode E; E.m_nValue = 3;
	BSTreeNode F; F.m_nValue = 5;
	BSTreeNode G; G.m_nValue = 7;
	D.m_pLeft = NULL;D.m_pRight = NULL;
	E.m_pLeft = NULL;E.m_pRight = NULL;
	F.m_pLeft = NULL;F.m_pRight = NULL;
	G.m_pLeft = NULL;G.m_pRight = NULL;
	B.m_pLeft  = &D;
	B.m_pRight = &E;
	C.m_pLeft  = &F;
	C.m_pRight = &G;
	A.m_pLeft  = &B;
	A.m_pRight = &C;
	BSTreeNode *LinkedList = treeToLinkedList(&A);
	while(LinkedList != NULL){
		cout<<LinkedList->m_nValue<<endl;
		LinkedList = LinkedList->m_pRight;
	}
	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值