题目1503:二叉搜索树与双向链表-九度

题目描述:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
输入:
输入可能包含多个测试样例。
对于每个测试案例,输入的第一行为一个数n(0<n<1000),代表测试样例的个数。
接下来的n行,每行为一个二叉搜索树的先序遍历序列,其中左右子树若为空则用0代替。
输出:
对应每个测试案例,
输出将二叉搜索树转换成排序的双向链表后,从链表头至链表尾的遍历结果。
样例输入:
1
2 1 0 0 3 0 0
样例输出:

1 2 3

推荐指数:※※

来源:http://ac.jobdu.com/problem.php?pid=1503

练习一下算法。

1.递归输入

2..对于将二叉搜索树转换成双向链表。其实就是:

     寻找节点左子树最大节点

     寻找节点右指数最小节点。 

      递归每个节点。

      使用原指针链接。

好吧,输出的每个数之后都要有空格。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
typedef struct node{
    int val;
    node *left;
    node *right;
}node;
node * input_tree(){
	int tmp;
	scanf("%d",&tmp);
	if(0==tmp){
		return NULL;
	}
	node *new_node=new node;
	new_node->val=tmp;
	new_node->left=input_tree();
	new_node->right=input_tree();
	return new_node;
}

void tree_to_link(node *root){
	if(root!=NULL){
        node *p=root->left;
        while(p!=NULL&&p->right!=NULL){// find it pre
            p=p->right;
        }
        node *q=root->right;
        while(q!=NULL&&q->left!=NULL){// find it next
            q=q->left;
        }
        tree_to_link(root->left);//handle left
        tree_to_link(root->right);//handle right
        if(p!=NULL){//link
            p->right=root;
            root->left=p;
        }
        if(q!=NULL){//link
            q->left=root;
            root->right=q;
        }
	} 
}
int main()
{
	int n;
	scanf("%d",&n);
	while(n--){
		node *t=new node;
		scanf("%d",&t->val);
		
		t->left=input_tree();    
		t->right=input_tree();    
		node *lhead=t;
		while(lhead!=NULL&&lhead->left!=NULL){
            lhead=lhead->left;
		}
		tree_to_link(t);
		while(lhead!=NULL){
            printf("%d ",lhead->val);
            lhead=lhead->right;
		}
		printf("\n");
	}
	return 0;
}


给一组测试数据:

2
7 5 4 0 0 6 0 0 9 8 0 0 10 0 0
2 1 0 0 3 0 0

你可能感兴趣的:(题目1503:二叉搜索树与双向链表-九度)