1. 程式人生 > >劍指offer——二叉查詢樹與雙向連結串列(36題)

劍指offer——二叉查詢樹與雙向連結串列(36題)

題目:輸入一棵二叉查詢樹,將該二叉查詢樹換成一個排序的雙向連結串列,要求不能建立任何新的節點,只能調整樹中節點指標的指向。

解題思想:又一是道二叉樹遍歷演算法的變型題,一定要往這個方向上面思考。此處採用中序遍歷(主體)演算法進行解題。

#include<iostream>

using namespace std;

struct TreeNode {
	int val;
	TreeNode* left, *right;
	TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};

//以下這個函式主體思想還是中序遍歷
void convertNode(TreeNode* root,TreeNode* &pLastNodeInList) {
	if (!root)
		return ;
	TreeNode* current = root;
	
	//遞迴進左子樹中
	if (root->left)
		convertNode(root->left, pLastNodeInList);

	//將尾結點與當前結點連線,構建雙向連結串列
	current->left = pLastNodeInList;
	if (pLastNodeInList)
		pLastNodeInList->right = current;
	pLastNodeInList = current;//將雙向連結串列的尾節點更改為當前結點

	//遞迴進右子樹中
	if (root->right)
		convertNode(root->right,pLastNodeInList);
}

TreeNode* convert(TreeNode* root) {
	if (!root)
		return nullptr;
	
	TreeNode* pLastNodeInList = nullptr;
	convertNode(root, pLastNodeInList);

	//由pLastNodeInList所指向開頭的節點向左的鏈
	while (pLastNodeInList->left) {
		pLastNodeInList = pLastNodeInList->left;
	}
	return pLastNodeInList;
}


//驗證部分
void Traverse(TreeNode* root) {
	if (!root)
		return;
	cout << root->val << " ";
	if (root->right)
		Traverse(root->right);
}

int main() {
	TreeNode a(10), b(6), c(14), d(4), e(8), f(12), g(16);
	a.left = &b;
	a.right = &c;
	b.left = &d;
	b.right = &e;
	c.left = &f;
	c.right = &g;

	TreeNode* cur = convert(&a);
	Traverse(cur);

	return 0;
}