Trees/DFS.js
// pre-order using Stack and tracking state
pre-order using Stack and tracking state
pre - order using Stack and tracking state
function pre_order_with_stack(tree){
  let visit_order = [];
  let stack = new Stack();
  let node = tree.get_root();
  visit_order.push(node.get_value());
  let state = new State(node);
  stack.push(state);
  let count = 0;
  while(node){
    count = count + 1;
    if (node.has_left_child() && !(state.get_visited_left()) ){
      state.set_visited_left();
      node = node.get_left_child();
      visit_order.push(node.get_value());
      state = new State(node);
      stack.push(state);
    }else if (node.has_right_child() && !(state.get_visited_right()) ){
      state.set_visited_right();
      node = node.get_right_child();
      visit_order.push(node.get_value());
      state = new State(node);
      stack.push(state);
    } else{
      stack.pop();
      if(stack.size() != 0){
        state = stack.top();
        node = state.get_node();
      }
      else{
        node = null;
      }
    }
  }
  return visit_order;
}
function pre_order_with_stack ( tree ) { let visit_order = [ ] ; let stack = new Stack ( ) ; let node = tree . get_root ( ) ; visit_order . push ( node . get_value ( ) ) ; let state = new State ( node ) ; stack . push ( state ) ; let count = 0 ; while ( node ) { count = count + 1 ; if ( node . has_left_child ( ) && ! ( state . get_visited_left ( ) ) ) { state . set_visited_left ( ) ; node = node . get_left_child ( ) ; visit_order . push ( node . get_value ( ) ) ; state = new State ( node ) ; stack . push ( state ) ; } else if ( node . has_right_child ( ) && ! ( state . get_visited_right ( ) ) ) { state . set_visited_right ( ) ; node = node . get_right_child ( ) ; visit_order . push ( node . get_value ( ) ) ; state = new State ( node ) ; stack . push ( state ) ; } else { stack . pop ( ) ; if ( stack . size ( ) != 0 ) { state = stack . top ( ) ; node = state . get_node ( ) ; } else { node = null ; } } } return visit_order ; }
pre-order using Stack and tracking state
pre - order using Stack and tracking state