将二元查找树转变为排序的双向链表

2011-04-25 20:52:50

例如:{10, 6, 14, 4, 8, 12, 16}的二叉搜索树,求双向链表输出:4=6=8=10=12=14=16

利用递归的特性不难写出Code:

 

/* * Copyright (c) 2011 alexingcool. All Rights Reserved. */ #include<iostream> #include<iterator> #include <algorithm> using namespace std; #define DEBUG struct Node { Node(int i, Node* l = NULL, Node* r = NULL) : item(i), left(l), right(r) {} int item; Node* left; Node* right; }; Node* construct() { Node* node6 = new Node(16); Node* node5 = new Node(12); Node* node4 = new Node(8); Node* node3 = new Node(4); Node* node2 = new Node(14, node5, node6); Node* node1 = new Node(6, node3, node4); Node* node0 = new Node(10, node1, node2); return node0; } Node *Reconstruct(Node *root) { static Node *head = NULL, *temp = NULL; if(root) { Reconstruct(root->left); if(head == NULL) { //要考虑为什么没有root->left = NULL head = root; temp = root; } else { temp->right = root; root->left = temp; temp = root; } Reconstruct(root->right); } return head; } void rprint(Node* root) { while(root) { cout << root->item << " "; root = root->right; } } void main() { Node *root = construct(); Node *head = Reconstruct(root); rprint(head); }

 

下面是上述方法的改写:

/* * Copyright (c) 2011 alexingcool. All Rights Reserved. */ #include <iostream> using namespace std; struct Node { Node(int i = 0, Node *pl = NULL, Node *pr = NULL) : data(i), left(pl), right(pr) {} int data; Node *left; Node *right; }; Node* Construct() { Node *node5 = new Node(16); Node *node4 = new Node(12); Node *node3 = new Node(8); Node *node2 = new Node(4); Node *node1 = new Node(14, node4, node5); Node *node0 = new Node(6, node2, node3); Node *root = new Node(10, node0, node1); return root; } void Convert(Node *root, Node *&head) { if(root == NULL) return; Convert(root->left, head); if(head == NULL) head = root; else { head->right = root; root->left = head; head = root; } Convert(root->right, head); } void print(Node *head) { while(head) { cout << head->data << " "; head = head->left; } } void InOrder(Node *root) { if(root) { InOrder(root->left); cout << root->data << " "; InOrder(root->right); } } void main() { Node *root = Construct(); Node *head = NULL; Node *pHead = head; InOrder(root); system("pause"); Convert(root, head); print(pHead); InOrder(root); }

 

思考:

1. 为什么最后中序遍历是4的循环打印?

2. 为什么这个改写方法不能在调用函数外面保存头结点,即pHead为什么无效?

3. 在调整指针指向的时候,只能修改root指针的left,而不能修改其right指针,否则将造成递归失败。


任何算法有递归解,就一定存在迭代算法,下面是迭代解法,本质上是利用前序遍历的迭代算法求解:

Node* Reconstruct2(Node *root)
{
	if (root == NULL)
		return NULL;

	Node *newRoot = NULL;
	Node *pNewRoot = newRoot;
	stack<Node *> nstack;
	Node *node = root;

	while (node != NULL || !nstack.empty())
	{
		while (node != NULL)
		{
			nstack.push(node);
			node = node->left;
		}

		node = nstack.top();

		if (newRoot == NULL)
		{
			newRoot = node;
			pNewRoot = newRoot;
		}
		else
		{
			pNewRoot->right = node;
			node->left = pNewRoot;
			pNewRoot = node;
		}

		node = node->right;
		nstack.pop();
	}

	return newRoot;
}


你可能感兴趣的:(c,null,System)