leetcode facebook面试 convert bst to double-linked list

题意:

convert  bst to double-linked list

代码:

struct BSTree {
	BSTree(int v) :val(v), left(NULL), right(NULL) {}
	~BSTree() {
		if (left) delete left;
		if (right) delete right;
	}
	int val;
	BSTree* left, *right;
};

struct  DoubleLinkedList {
	DoubleLinkedList(int v) : val(v), prev(NULL), next(NULL) {}
	~DoubleLinkedList() {
		if (next)
			delete next;
	}
	DoubleLinkedList *prev, *next;
	int val;

};

void insert(int val, BSTree*& root) {
	if (!root)
		root = new BSTree(val);
	else if (root->val > val)
		insert(val, root->left);
	else if (root->val < val)
		insert(val, root->right);
}
BSTree* buildBST() {
	ifstream ifstr("bst_to_double_linked_list.txt");
	if (!ifstr)
		assert(0);
	string line;
	getline(ifstr, line);
	int val;
	istringstream istringstr(line);
	BSTree* root = NULL;
	while (istringstr >> val) {
		insert(val, root);
	}
	return root;
}
void traverse_tree(BSTree* root) {
	if (root) {
		traverse_tree(root->left);
		cout << root->val << endl;
		traverse_tree(root->right);
	}
}

// 理解这两个指针引用,特别是第一个:prevElem
void convert_bst_to_dllist(BSTree* root, DoubleLinkedList* & prevElem, DoubleLinkedList*& head) {
	if (root->left)
		convert_bst_to_dllist(root->left, prevElem, head);
	DoubleLinkedList* newElem = new 	DoubleLinkedList(root->val);
	if (prevElem) {
		prevElem->next = newElem;
		newElem->prev = prevElem;
	}
	if (head == NULL)
		head = newElem;
	prevElem = newElem;
	if (root->right)
		convert_bst_to_dllist(root->right, prevElem, head);
}
void traverse_dllist(DoubleLinkedList* list_head) {
	cout << "positive sequence:" << endl;
	while (list_head && list_head->next) {
		cout << list_head->val << " ";
		list_head = list_head->next;
	}
	if (list_head)
		cout << list_head->val << endl;
	cout << "negative sequence:" << endl;
	while (list_head && list_head->prev) {
		cout << list_head->val << " ";
		list_head = list_head->prev;
	}
	if (list_head)
		cout << list_head->val << endl;
}

int main() {
	BSTree* root = buildBST();
	//traverse_tree(root);
	DoubleLinkedList* list_head = NULL, *prevElem = NULL;
	if (root)
		convert_bst_to_dllist(root, prevElem, list_head);
	if (list_head)
		traverse_dllist(list_head);
	delete list_head;
	delete root;
	
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值