码迷,mamicode.com
首页 > 其他好文 > 详细

1310. Right-Heavy Tree

时间:2015-01-13 21:44:22      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:算法   c++   sicily   遍历   

#include "iostream"
#include "cstdio"
using namespace std;

struct Node{
	int val;
	Node *left, *right;
	Node(int v = 0){
		val = v;
		left = NULL;
		right = NULL;
	}
};

inline void preOrder(Node *head){ //一定要加上inline才能过,否则会time limit
	if (head != NULL){
		printf(" %d", head->val);
		preOrder(head->left);
		preOrder(head->right);
	}
}
inline  void inOrder(Node *head){
	if (head != NULL){		
		inOrder(head->left);
		printf(" %d", head->val);
		inOrder(head->right);
	}
}

inline  void postOrder(Node *head){
	if (head != NULL){
		postOrder(head->left);
		postOrder(head->right);
		printf(" %d", head->val);
	}
}

inline  void buildTree(Node *&head, const int value){ //这里使用指针引用
	if (head == NULL){
		head = new Node(value);
	}
	else {
		if (head->val < value){
			buildTree(head->right ,value);
		}
		else
			buildTree(head->left, value);
	}
}

int main(){
	int n;
	bool ok = false;
	while (scanf("%d", &n) != EOF){
		if (ok)
			printf("\n");
		ok = true;
		Node *root = NULL;
		for (int i = 0; i < n; i++){
			int tmp;
			scanf("%d", &tmp);
			buildTree(root, tmp);
		}

		printf("Inorder:");
		inOrder(root);
		printf("\n");
		printf("Preorder:");
		preOrder(root);
		printf("\n");
		printf("Postorder:");
		postOrder(root);
		printf("\n");
	}
	return 0;
}

1310. Right-Heavy Tree

标签:算法   c++   sicily   遍历   

原文地址:http://blog.csdn.net/liujan511536/article/details/42681349

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!