Loading [MathJax]/extensions/TeX/AMSsymbols.js

2016年3月13日 星期日

Uva 12347 Binary Search Tree

題目來源:https://uva.onlinejudge.org/external/123/12347.pdf

題意:將輸入的pre_order的Binary tree轉成post_order

做法:直接建議棵樹,再用Postorder(左->右->中)輸出

程式碼:


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
class Tree
{
private:
struct node
{
int value = 0;
node *left = nullptr;
node *right = nullptr;
};
node* root = nullptr;
public:
Tree();
~Tree();
void insert(int);
void Postorder();
void print_postorder(node*);
};
Tree::Tree()
{
}
Tree::~Tree()
{
}
void Tree::insert(int new_node)
{
node *tree = new node;
node *parent = new node;
tree->value = new_node;
tree->right = nullptr;
tree->left = nullptr;
parent = nullptr;
if (root == nullptr) {
root = tree;
return;
}
node* v = root;
while (v) {
parent = v;
if (parent->value > new_node) {
v = parent->left;
}
else {
v = parent->right;
}
}
if (parent->value > new_node) {
parent->left = tree;
}
else {
parent->right = tree;
}
}
void Tree::Postorder()
{
print_postorder(root);
}
void Tree::print_postorder(node *n)
{
if (n == nullptr) {
return;
}
print_postorder(n->left);
print_postorder(n->right);
printf("%d\n", n->value);
}
int main() {
Tree tree;
int x;
while (cin >> x) {
tree.insert(x);
}
tree.Postorder();
system("PAUSE");
}
view raw Uva 12347.cpp hosted with ❤ by GitHub





沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。