俊介三

一天更新一点,一天积累一点

导航

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

Posted on 2013-03-27 19:31  俊介三在前进  阅读(139)  评论(0)    收藏  举报

题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。

思路:可以看到双链表的排序是二叉树中序遍历的结果。因此,我们可以中序遍历二叉树,每次访问一个节点,就把它添加进我们的双链表来,注意,添加的意思是是改变一个指针而已,不需要额外的空间。。当然,需要记录一下双链表的头,以及每一次双链最后那个node。

见代码:

#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include <queue>

using namespace std;

struct Node{
    int data;
    Node* left;
    Node* right;
    Node(){}
    Node(int d){
        data = d;
        left = NULL;
        right = NULL;
    }
};

void inorder(Node* root){
    if(root==NULL) return;
    inorder(root->left);
    printf("%d ",root->data);
    inorder(root->right);
}

//////////////
Node* pre=NULL;  //上一个节点
Node* head=NULL;  //头节点
void add2List(Node* node){
    if(pre==NULL){
        pre = node;
        head = node;
    }else{
        pre->right = node;
        node->left = pre;
        pre = node;
    }
}

void tree2List(Node* current){
    if(current==NULL) return;
    tree2List(current->left);
    add2List(current);
    tree2List(current->right);
}

int main(){
    Node* root = new Node(1);
    Node* n1 = new Node(2);
    Node* n2 = new Node(3);
    Node* n3 = new Node(4);
    Node* n4 = new Node(5);
    Node* n5 = new Node(6);
    Node* n6 = new Node(7);
    Node* n7 = new Node(8);
    root->left = n1;
    root->right = n2;
    n1->left = n3;
    n1->right = n4;
    n2->left = n5;
    n2->right = n6;
    n3->left = n7;
    
    inorder(root);
    puts("");

    tree2List(root);
    while(head!=NULL){
        printf("%d ",head->data);
        head = head->right;
    }
    puts("");
    
    return 0;
}