2016/11/10 1002. 二叉查找树的遍历

来源:互联网 发布:域名别名解析 编辑:程序博客网 时间:2024/05/17 02:15

先按输入构建出二叉树,然后遍历即可。二叉查找树的建立不难,对每一个输入,从根节点出发,小的往左,大的往右,若空则插入即可。

#include <iostream>using namespace std;class Node{public:Node(int a = 0){v = a;left = nullptr;right = nullptr;}Node *left;Node *right;int v;};class Tree{public:Tree(int a=0){root = new Node(a);}void insert(int a){Node* p = root;for (;;){if (a > p->v){if (p->right == nullptr){p->right = new Node(a);break;}else{p = p->right;continue;}}if (a < p->v){if (p->left == nullptr){p->left = new Node(a);break;}else{p = p->left;continue;}}}}Node *root;};void inorder(Node *root){if (root == nullptr){return;}inorder(root->left);cout << root->v << " ";inorder(root->right);}void preorder(Node *root){if (root == nullptr){return;}cout << root->v << " ";preorder(root->left);preorder(root->right);}int main(){int t;for (;;){cin >> t;if (t == 0)break;int temp;cin >> temp;Tree T(temp);for (int i = 2; i <= t; i++){int a;cin >> a;T.insert(a);}inorder(T.root);cout << endl;preorder(T.root);cout << endl;}}


0 0