preorder tree construction: much better algorithm. No need to keep root.

This commit is contained in:
2018-02-04 10:40:31 +00:00
parent 08e93603a9
commit cdfa46e84c

View File

@@ -5,17 +5,16 @@ VIM: let b:argv=""
*/ */
#include <vector> #include <vector>
#include <string> #include <string>
#include <stack>
#include <iostream> #include <iostream>
struct node { struct node {
node * root = nullptr;
node * left = nullptr; node * left = nullptr;
node * right = nullptr; node * right = nullptr;
double data = 0; double data = 0;
node( double d, node * r = nullptr ) node( double d )
: root(r) : data(d)
, data(d)
{} {}
}; };
@@ -26,35 +25,26 @@ node * prefix_to_tree( const std::vector<double>& v ){
} }
node * root = new node(v[0]); node * root = new node(v[0]);
node * current = root;
node * max_node = nullptr; std::stack<node*> stack;
stack.push(root);
for ( int i = 1; i < v.size(); ) { for ( int i = 1; i < v.size(); ) {
if ( v[i] < current->data ){ if ( v[i] < stack.top()->data ){
max_node = current; auto n = new node(v[i++]);
current = new node(v[i++],current); stack.top()->left = n;
current->root->left = current; stack.push(n);
} else if ( !max_node
|| v[i] < max_node->data ){
current = new node(v[i++],current);
current->root->right = current;
} else if ( current->root ){
current = current->root;
while ( max_node
&& max_node->data <= current->data ) {
node * tmp = max_node;
max_node = max_node->root;
if ( max_node && tmp == max_node->left ){
break;
}
}
} else { } else {
std::cout << "error" << std::endl; auto c = stack.top();
break; stack.pop();
} while( !stack.empty() && stack.top()->data < v[i] ){
c = stack.top();
stack.pop();
}
if ( !current || !root ) { auto n = new node(v[i++]);
std::cout << "errrrrrror" << std::endl; c->right = n;
stack.push(n);
} }
} }