How to convert bottom-up recursive algorithm to iterative stack in JavaScript

前端 未结 4 916
醉梦人生
醉梦人生 2021-01-20 20:00

Given the following algorithm:

4条回答
  •  醉酒成梦
    2021-01-20 21:01

    Let's start with just the is:

    function create(i) {
      console.log(i)
    
      if (i == 3) return
    
      return new Klass(i, create(i+1), create(i+1))
    }
    
    function Klass(i, l, r) {
      this.i = i
      this.l = l
      this.r = r
    }
    
    console.log(JSON.stringify(create(0)))
    
    console.log('\nStack version:')
    
    let stack = [0];
    
    while (stack.length){
      let i = stack.pop();
    
      console.log(i);
    
      if (i < 3)
        stack.push(i + 1, i + 1);
    }

    There are so many ways we could use the iteratively generated order of is; from pushing them all to an array, then following the trail of assignments backwards; to using the i to create a new Klass and passing it by reference, essentially turning the process into top-down.

提交回复
热议问题