Performing Breadth First Search recursively

后端 未结 21 2625
不思量自难忘°
不思量自难忘° 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 01:40

    I had to implement a heap traversal which outputs in a BFS order. It isn't actually BFS but accomplishes the same task.

    private void getNodeValue(Node node, int index, int[] array) {
        array[index] = node.value;
        index = (index*2)+1;
    
        Node left = node.leftNode;
        if (left!=null) getNodeValue(left,index,array);
        Node right = node.rightNode;
        if (right!=null) getNodeValue(right,index+1,array);
    }
    
    public int[] getHeap() {
        int[] nodes = new int[size];
        getNodeValue(root,0,nodes);
        return nodes;
    }
    

提交回复
热议问题