现在的位置: 首页 > 综合 > 正文

HDU3999

2013年09月05日 ⁄ 综合 ⁄ 共 682字 ⁄ 字号 评论关闭
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct TNode{
	int v;
	struct TNode *left, *right;
}Node;//建立节点

Node *Buildtree(Node * root, int n){
	
		if(root == NULL){
			root = (Node*)malloc(sizeof(Node));	
			root -> v = n; 
			root -> left = root -> right = NULL;
			return root;
		}	
		if(root -> v > n )
			root -> left = Buildtree(root -> left, n);	
		else	
			root -> right = Buildtree(root -> right, n);	
		return root;//每次返回头指针,才能进行下一次的比较	
}//建树	
		
void DLR(Node *root, int n)//前序遍历
{		
		
		if(n != 1)
	  	 	printf(" %d", root -> v);
	   	else
			printf("%d", root -> v);	
		if(root -> left != NULL)	
			DLR(root -> left, 2);
		if(root -> right != NULL)
			DLR(root -> right, 2);	
	 
} 

int main(){

	int n, m, i;
	Node * root = NULL;	
	while(scanf("%d", &n) != EOF){
		
		for(i = 0;i < n; i++)
		{
			scanf("%d", &m);
			root = Buildtree(root, m);
		}	
			DLR(root, 1);	
			printf("\n");
			

	}

return 0;
}

抱歉!评论已关闭.