From cdfa46e84c44e54f8a2333153af7bc2804dd0293 Mon Sep 17 00:00:00 2001 From: Vahagn Khachatryan Date: Sun, 4 Feb 2018 10:40:31 +0000 Subject: [PATCH] preorder tree construction: much better algorithm. No need to keep root. --- .../training/preorder_tree_construction.cpp | 48 ++++++++----------- 1 file changed, 19 insertions(+), 29 deletions(-) diff --git a/puzzles/interviews/training/preorder_tree_construction.cpp b/puzzles/interviews/training/preorder_tree_construction.cpp index e2c24ae..e41fcd1 100644 --- a/puzzles/interviews/training/preorder_tree_construction.cpp +++ b/puzzles/interviews/training/preorder_tree_construction.cpp @@ -5,17 +5,16 @@ VIM: let b:argv="" */ #include #include +#include #include 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& v ){ } node * root = new node(v[0]); - node * current = root; - node * max_node = nullptr; + + std::stack 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); } }