preorder tree construction: much better algorithm. No need to keep root.
This commit is contained in:
@@ -5,17 +5,16 @@ VIM: let b:argv=""
|
||||
*/
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <stack>
|
||||
#include <iostream>
|
||||
|
||||
struct node {
|
||||
node * root = nullptr;
|
||||
node * left = nullptr;
|
||||
node * right = nullptr;
|
||||
double data = 0;
|
||||
|
||||
node( double d, node * r = nullptr )
|
||||
: root(r)
|
||||
, data(d)
|
||||
node( double d )
|
||||
: data(d)
|
||||
{}
|
||||
};
|
||||
|
||||
@@ -26,35 +25,26 @@ node * prefix_to_tree( const std::vector<double>& v ){
|
||||
}
|
||||
|
||||
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(); ) {
|
||||
if ( v[i] < current->data ){
|
||||
max_node = current;
|
||||
current = new node(v[i++],current);
|
||||
current->root->left = current;
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
if ( v[i] < stack.top()->data ){
|
||||
auto n = new node(v[i++]);
|
||||
stack.top()->left = n;
|
||||
stack.push(n);
|
||||
} else {
|
||||
std::cout << "error" << std::endl;
|
||||
break;
|
||||
}
|
||||
auto c = stack.top();
|
||||
stack.pop();
|
||||
while( !stack.empty() && stack.top()->data < v[i] ){
|
||||
c = stack.top();
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
if ( !current || !root ) {
|
||||
std::cout << "errrrrrror" << std::endl;
|
||||
auto n = new node(v[i++]);
|
||||
c->right = n;
|
||||
stack.push(n);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user