歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 二叉查找樹轉換成排序的雙向鏈表

二叉查找樹轉換成排序的雙向鏈表

日期:2017/3/1 9:29:48   编辑:Linux編程

題目:輸入一棵二元查找樹,將該二元查找樹轉換成一個排序的雙向鏈表。要求不能創建任何新的結點,只調整指針的指向。
比如將二元查找樹
10
/ \
6 14
/ \ / \
4 8 12 16
轉換成雙向鏈表

4=6=8=10=12=14=16。

思路:對於樹的很多題目,都可以使用遞歸的方法來處理。這道題目也不例外。我們從最基本的思路來考慮這個題目。

把一個二叉樹編程雙向鏈表,最終是一個有序的序列,也就是中序遍歷之後的結果,那麼當我們采用中序遍歷的方式遍歷二叉樹時,遍歷到某個節點,是的前序節點的右指針指向當前節點,然後當前節點的左指針指向前序節點,然後使得前序節點指向當前節點。

BinTree* head =NULL;
void helper(BinTree* root,BinTree*& pre)
{
if(root == NULL && root == NULL)
return ;

helper(root->left,pre);
if(head == NULL)
head = root;
if(pre == NULL)
pre = root;
else
{
root->left = pre;
pre->right = root;
pre = root;
}
//cout<<root->value<<" "<<endl;
helper(root->right,pre);
}
BinTree* SearchTreeConverstToList(BinTree* root)
{
BinTree* pre = NULL;
helper(root,pre);
return head;
}

思路二:如果對於當前節點,我們把右子樹轉換成雙向鏈表,然後把左子樹轉換成雙向鏈表,轉換的時候我們都標記了鏈表的頭節點和尾節點,那麼我們只需要將當前節點和左子樹的尾部相連,和右子樹的頭部相連即可。

void helper_second(BinTree* root,BinTree*& head,BinTree*& tail)
{
if(root==NULL || (root->left == NULL && root->right == NULL))
{
head = root;
tail = root;
return;
}
BinTree* left_head = NULL;
BinTree* left_tail = NULL;
BinTree* right_head = NULL;
BinTree* right_tail = NULL;

helper_second(root->left,left_head,left_tail);
helper_second(root->right,right_head,right_tail);

if(left_head == NULL)
head = root;
else
{
head = left_head;
left_tail->right = root;
root->right = left_tail;
}
if(right_head == NULL)
tail = root;
else
{
tail = right_tail;
root->right = right_head;
right_head->left = root;
}
}

BinTree* ConverstToList(BinTree* root)
{
BinTree* head=NULL;
BinTree* tail = NULL;
helper_second(root,head,tail);
return head;
}

二叉樹的常見問題及其解決程序 http://www.linuxidc.com/Linux/2013-04/83661.htm

【遞歸】二叉樹的先序建立及遍歷 http://www.linuxidc.com/Linux/2012-12/75608.htm

在JAVA中實現的二叉樹結構 http://www.linuxidc.com/Linux/2008-12/17690.htm

【非遞歸】二叉樹的建立及遍歷 http://www.linuxidc.com/Linux/2012-12/75607.htm

二叉樹遞歸實現與二重指針 http://www.linuxidc.com/Linux/2013-07/87373.htm

二叉樹先序中序非遞歸算法 http://www.linuxidc.com/Linux/2014-06/102935.htm

輕松搞定面試中的二叉樹題目 http://www.linuxidc.com/linux/2014-07/104857.htm

Copyright © Linux教程網 All Rights Reserved