Performing Breadth First Search recursively

后端 未结 21 2525
不思量自难忘°
不思量自难忘° 2020-11-28 01:12

Let\'s say you wanted to implement a breadth-first search of a binary tree recursively. How would you go about it?

Is it possible using only the call-stack

21条回答
  •  清酒与你
    2020-11-28 02:04

    Here is a JavaScript Implementation that fakes Breadth First Traversal with Depth First recursion. I'm storing the node values at each depth inside an array, inside of a hash. If a level already exists(we have a collision), so we just push to the array at that level. You could use an array instead of a JavaScript object as well since our levels are numeric and can serve as array indices. You can return nodes, values, convert to a Linked List, or whatever you want. I'm just returning values for the sake of simplicity.

    BinarySearchTree.prototype.breadthFirstRec = function() {
    
        var levels = {};
    
        var traverse = function(current, depth) {
            if (!current) return null;
            if (!levels[depth]) levels[depth] = [current.value];
            else levels[depth].push(current.value);
            traverse(current.left, depth + 1);
            traverse(current.right, depth + 1);
        };
    
        traverse(this.root, 0);
        return levels;
    };
    
    
    var bst = new BinarySearchTree();
    bst.add(20, 22, 8, 4, 12, 10, 14, 24);
    console.log('Recursive Breadth First: ', bst.breadthFirstRec());
    /*Recursive Breadth First:  
    { '0': [ 20 ],
      '1': [ 8, 22 ],
      '2': [ 4, 12, 24 ],
      '3': [ 10, 14 ] } */
    

    Here is an example of actual Breadth First Traversal using an iterative approach.

    BinarySearchTree.prototype.breadthFirst = function() {
    
        var result = '',
            queue = [],
            current = this.root;
    
        if (!current) return null;
        queue.push(current);
    
        while (current = queue.shift()) {
            result += current.value + ' ';
            current.left && queue.push(current.left);
            current.right && queue.push(current.right);
        }
        return result;
    };
    
    console.log('Breadth First: ', bst.breadthFirst());
    //Breadth First:  20 8 22 4 12 24 10 14
    

提交回复
热议问题